@ngockhoale/ukit 3.5.5 → 3.5.7

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 (59) hide show
  1. package/CHANGELOG.md +25 -0
  2. package/manifests/engineConformance.yaml +0 -13
  3. package/manifests/platform.full.yaml +25 -0
  4. package/package.json +1 -8
  5. package/src/cli/commands/indexTools.js +1 -0
  6. package/src/cli/commands/memory.js +33 -4
  7. package/src/core/applyPlan.js +37 -72
  8. package/src/core/diffPlan.js +39 -9
  9. package/src/core/managedTemplateMerge.js +231 -0
  10. package/src/core/memory/memoryFlags.js +5 -6
  11. package/src/core/memory/policy.js +5 -0
  12. package/src/core/memory/store.js +17 -0
  13. package/src/core/metadata.js +12 -8
  14. package/src/core/runInstallPipeline.js +16 -10
  15. package/src/core/runtimeConfig.js +14 -83
  16. package/src/core/uninstall.js +8 -1
  17. package/src/decision/registry.js +17 -17
  18. package/src/decision/runtimeDecide.js +5 -5
  19. package/src/index/playbookRegistry.js +6 -1
  20. package/src/index/queryIndex.js +41 -4
  21. package/src/index/routeResolver.js +2 -2
  22. package/src/index/semanticLane.js +277 -0
  23. package/src/learning/lessonClass.js +110 -0
  24. package/src/learning/patternProposals.js +111 -7
  25. package/src/learning/reeditMiner.js +104 -0
  26. package/src/learning/selfImprove.js +9 -1
  27. package/template_project/.claude/hooks/skill-router.sh +273 -5
  28. package/template_project/.claude/skills/canvas-design/SKILL.md +2 -2
  29. package/template_project/.claude/skills/canvas-design/canvas-fonts/{InstrumentSans-OFL.txt → InstrumentSerif-OFL.txt} +3 -3
  30. package/template_project/.claude/skills/canvas-design/scripts/fetch-fonts.mjs +148 -0
  31. package/template_project/.claude/ukit/index/embed-index.mjs +26 -0
  32. package/template_project/.claude/ukit/index/lib/index-core.mjs +43 -4
  33. package/template_project/.claude/ukit/index/lib/semantic-lane.mjs +277 -0
  34. package/template_project/.claude/ukit/index/playbook-registry.mjs +6 -1
  35. package/template_project/.claude/ukit/index/publication-intent.mjs +159 -1
  36. package/template_project/.claude/ukit/index/query-index.mjs +9 -1
  37. package/template_project/.claude/ukit/index/route-resolver.mjs +2 -2
  38. package/template_project/.claude/ukit/index/route-task.mjs +14 -3
  39. package/template_project/.claude/ukit/runtime/memory-policy.mjs +5 -0
  40. package/template_project/.claude/ukit/runtime/stop-coordinator.mjs +12 -1
  41. package/template_project/ukit/storage/config.json +0 -32
  42. package/template_project/.claude/skills/canvas-design/canvas-fonts/BricolageGrotesque-Bold.ttf +0 -0
  43. package/template_project/.claude/skills/canvas-design/canvas-fonts/BricolageGrotesque-OFL.txt +0 -93
  44. package/template_project/.claude/skills/canvas-design/canvas-fonts/BricolageGrotesque-Regular.ttf +0 -0
  45. package/template_project/.claude/skills/canvas-design/canvas-fonts/InstrumentSans-Bold.ttf +0 -0
  46. package/template_project/.claude/skills/canvas-design/canvas-fonts/InstrumentSans-BoldItalic.ttf +0 -0
  47. package/template_project/.claude/skills/canvas-design/canvas-fonts/InstrumentSans-Italic.ttf +0 -0
  48. package/template_project/.claude/skills/canvas-design/canvas-fonts/InstrumentSans-Regular.ttf +0 -0
  49. package/template_project/.claude/skills/canvas-design/canvas-fonts/InstrumentSerif-Italic.ttf +0 -0
  50. package/template_project/.claude/skills/canvas-design/canvas-fonts/JetBrainsMono-Bold.ttf +0 -0
  51. package/template_project/.claude/skills/canvas-design/canvas-fonts/Lora-Bold.ttf +0 -0
  52. package/template_project/.claude/skills/canvas-design/canvas-fonts/Lora-BoldItalic.ttf +0 -0
  53. package/template_project/.claude/skills/canvas-design/canvas-fonts/Lora-Italic.ttf +0 -0
  54. package/template_project/.claude/skills/canvas-design/canvas-fonts/Lora-OFL.txt +0 -93
  55. package/template_project/.claude/skills/canvas-design/canvas-fonts/Lora-Regular.ttf +0 -0
  56. package/template_project/.claude/skills/canvas-design/canvas-fonts/Outfit-Bold.ttf +0 -0
  57. package/template_project/.claude/skills/canvas-design/canvas-fonts/Tektur-Medium.ttf +0 -0
  58. package/template_project/.claude/skills/canvas-design/canvas-fonts/YoungSerif-OFL.txt +0 -93
  59. package/template_project/.claude/skills/canvas-design/canvas-fonts/YoungSerif-Regular.ttf +0 -0
@@ -96,12 +96,31 @@ try {
96
96
  }
97
97
  return text;
98
98
  });
99
- const block = (name) => new RegExp(`^<${name}(?:\\s[^>]*)?>[\\s\\S]*<\\/${name}>$`, "i");
99
+ // A value is internal only when it is a SEQUENCE of closed blocks of one tag with nothing but
100
+ // whitespace between them. A greedy open...close match would swallow owner text sitting between two
101
+ // blocks (block, owner order, block) and silently drop that order.
102
+ const block = (name) => ({
103
+ test(value) {
104
+ const one = new RegExp(`^<${name}(?:\\s[^>]*)?>[\\s\\S]*?<\\/${name}>\\s*`);
105
+ let rest = String(value);
106
+ let n = 0;
107
+ for (let m = one.exec(rest); m; m = one.exec(rest)) { rest = rest.slice(m[0].length); n += 1; }
108
+ return n > 0 && rest === "";
109
+ },
110
+ });
100
111
  const internal = candidates.some((value) => (
101
112
  block("task-notification").test(value)
102
113
  || block("tool-result").test(value)
103
114
  || block("system-reminder").test(value)
104
- || /^<local-command-caveat(?:\s[^>]*)?>[\s\S]*<\/local-command-stdout>$/i.test(value)
115
+ || ((value) => {
116
+ // Host caveat echo: same shape as before (caveat open ... stdout close), but as a sequence of
117
+ // lazy units so owner text between two echoes is never swallowed.
118
+ const one = /^<local-command-caveat(?:\s[^>]*)?>[\s\S]*?<\/local-command-stdout>\s*/;
119
+ let rest = String(value);
120
+ let n = 0;
121
+ for (let m = one.exec(rest); m; m = one.exec(rest)) { rest = rest.slice(m[0].length); n += 1; }
122
+ return n > 0 && rest === "";
123
+ })(value)
105
124
  ));
106
125
  process.stdout.write(internal ? "1" : "0");
107
126
  } catch {
@@ -198,12 +217,26 @@ const { pathToFileURL } = require('url');
198
217
  const { spawn } = require('child_process');
199
218
 
200
219
  const HOOK_DEADLINE_MS = Number.parseInt(process.env.UKIT_HOOK_DEADLINE_MS || '', 10) || 3000;
201
- setTimeout(() => process.exit(0), HOOK_DEADLINE_MS).unref();
220
+ // A deadline kill is exit 0. When the kill lands inside the window where a fresh owner prompt has
221
+ // not yet published its route, the previous (armed) contract would stay live for the new prompt; the
222
+ // handler installed below writes a bounded pending marker first so readers fail closed instead.
223
+ // Every other kill exits at once. The second timer is armed first and guarantees exit even if that write
224
+ // hangs (worst case: deadline + 400 ms + the 300 ms bounded exit-fold spin; no sync fs is added here).
225
+ // LIMIT: a timer cannot fire during synchronous work, only at the next await after the deadline; a sync
226
+ // stretch that outlives the host's own hook budget is killed by the host with no marker (3.5.6 behaviour).
227
+ let deadlineReached = false;
228
+ let deadlineHandler = null;
229
+ setTimeout(() => {
230
+ deadlineReached = true;
231
+ if (!deadlineHandler) process.exit(0);
232
+ setTimeout(() => process.exit(0), 400).unref();
233
+ try { Promise.resolve(deadlineHandler()).then(() => process.exit(0), () => process.exit(0)); } catch { process.exit(0); }
234
+ }, HOOK_DEADLINE_MS).unref();
202
235
 
203
236
  (async () => {
204
- // BEGIN GENERATED SEMANTIC ENGINE sha256=db789c44db60937d51b7d9a4a9481264feb9f7152b88721bc973a16c4129f7fc
237
+ // BEGIN GENERATED SEMANTIC ENGINE sha256=c75ad63540825f83a0b87d35aa14cd05c536b950b6b97aef8f9a3fe3767f59cf
205
238
  // Canonical task semantics; intent never grants authorization or proves completion.
206
- const SEMANTIC_ENGINE_VERSION = 'round4-semantic-1:86afd8b71e068da6a63a85fcf003f79be262881f6c203fa44682853cf8acb4f7';
239
+ const SEMANTIC_ENGINE_VERSION = 'round4-semantic-1:02b15877348961e92a6d682beeb94b0dde7e116fb2b2ba9b5c419147772732f8';
207
240
 
208
241
  function semanticContractIdentity({ promptText = '', targetFile = '', taskInstanceId = null } = {}) {
209
242
  return { taskInstanceId, targetFile, engineVersion: SEMANTIC_ENGINE_VERSION,
@@ -226,7 +259,24 @@ function compareSemanticContracts({ stored, fresh, previousIdentity, identity })
226
259
  }
227
260
  const foldIntent = (text) => String(text).normalize('NFD').replace(/[̀-ͯ]/g, '').replace(/[đĐ]/g, 'd').toLowerCase();
228
261
 
262
+ // The analysers are pure functions of their arguments but one hook run asks the same question about the same
263
+ // prompt dozens of times. Memoise per exact input (bounded, insertion-order eviction) and hand every caller its
264
+ // own structuredClone, so no caller can mutate the cache or another caller's result.
265
+ const SEMANTIC_MEMO_LIMIT = 16;
266
+ const memoCloned = (cache, key, compute) => {
267
+ const hit = cache.get(key);
268
+ if (hit !== undefined) return structuredClone(hit);
269
+ const value = compute();
270
+ if (cache.size >= SEMANTIC_MEMO_LIMIT) cache.delete(cache.keys().next().value);
271
+ cache.set(key, structuredClone(value));
272
+ return value;
273
+ };
274
+ const analyzeMemo = new Map();
229
275
  function analyzeTaskIntent({ promptText = '', targetFile = '', taskInstanceId = null, sessionId = null } = {}) {
276
+ return memoCloned(analyzeMemo, JSON.stringify([String(promptText), targetFile, taskInstanceId, sessionId]),
277
+ () => analyzeTaskIntentUncached({ promptText, targetFile, taskInstanceId, sessionId }));
278
+ }
279
+ function analyzeTaskIntentUncached({ promptText = '', targetFile = '', taskInstanceId = null, sessionId = null } = {}) {
230
280
  const original = String(promptText);
231
281
  const spans = [];
232
282
  let fence = null;
@@ -415,7 +465,11 @@ function classifyProhibitionItem(item, authorized, proper) {
415
465
  return null;
416
466
  }
417
467
 
468
+ const scopeMemo = new Map();
418
469
  function publicationScope(promptText = '') {
470
+ return memoCloned(scopeMemo, String(promptText), () => publicationScopeUncached(promptText));
471
+ }
472
+ function publicationScopeUncached(promptText = '') {
419
473
  const plain = String(promptText).normalize('NFC')
420
474
  .replace(/\bdùng\b/giu, 'su dung').replace(/đừng/giu, 'khong')
421
475
  .replace(/(^|[\n;.]\s*)([ \t]*(?:[-*+•]|\d+[.)])?[ \t]*)dung(?=\s+(?:publish|release|npm|git|run|fix|sua)\b)/gi, '$1$2khong')
@@ -736,8 +790,139 @@ const OWNER_STOP_EN = /^(?:please\s+)?(?:stop|halt|pause|cancel|abort)(?:\s+(?:a
736
790
  const OWNER_STOP_VI = /^(?:(?:tam\s+)?(?:dừng|ngừng)|(?:tạm\s+)?(?:dừng|ngừng)|hủy|huỷ|tam\s+dung|tam\s+ngung|ngung|dung\s+(?:lai|thuc\s+thi|ngay)|huy)(?:\s+(?:thực\s+thi|thuc\s+thi|phiên\s+này|phien\s+nay|phiên|phien|lại|lai|ngay|ngay\s+lập\s+tức|tất\s+cả|tat\s+ca|mọi\s+thứ|moi\s+thu|việc|viec|công\s+việc|cong\s+viec|run|handoff|session|task))*$/;
737
791
  const OWNER_CONTROL_TASK_WORD = /\b(?:fix|implement|add|update|edit|write|create|deploy|redeploy|publish|commit|refactor|rewrite|install|sua|sửa|them|thêm|chay|chạy|cap nhat|cập nhật)\b|[\w-]+\/[\w.-]+/;
738
792
  const OWNER_CONTROL_TASK_LEAD = /^(?:(?:and\s+)?then|also|afterwards?|after that|next|now|sau do|sau đó|roi|rồi|va|và)\b|^(?:please\s+)?(?:fix|implement|add|update|edit|write|create|run|deploy|redeploy|publish|commit|push|refactor|rewrite|install|build|sua|sửa|them|thêm|chay|chạy|trien khai|triển khai|cap nhat|cập nhật)\b/;
793
+ // A STANDING POLICY states how the owner wants bugs handled in general ("luôn nhớ: có bug là phải fix ngay",
794
+ // "always remember: any bug must be fixed immediately, at its root cause"). It names no defect, so it owes no
795
+ // repro/root-cause contract. CLOSED GRAMMAR: the prompt is split into clauses and returns true ONLY if EVERY
796
+ // non-empty clause, whole and anchored (^...$), is one of the enumerated forms below, and at least one clause is
797
+ // a defect rule. No clause is skipped (only clauses of pure whitespace/punctuation are empty), no clause passes
798
+ // by "all its words are in a set", and no script is exempt: text in any alphabet that matches no form is an
799
+ // order. Any doubt returns false (a real bug order keeps its full evidence duty; a wrong release is the worse
800
+ // error). Global rejects first: concrete referent (path/identifier/quote/version/URL/exit code), a symptom
801
+ // statement, a deictic aimed at a present defect, no policy marker anywhere. The splitter (SP_CLAUSE_SPLIT)
802
+ // cuts on punctuation/newline ONLY and never contains a letter, so no connector word is dropped unjudged;
803
+ // "và" exists only inside form RC. Clause forms (judged on raw NFC text, accents exact, see below):
804
+ // F1 MARK a marker phrase alone ("luôn nhớ", "from now on", "nguyên tắc của tôi")
805
+ // R1 [MARK] (có|thấy|gặp|phát hiện) DEF (là|thì) [phải|luôn] FIX ADV*
806
+ // R2 [MARK] mọi DEF [là|đều] phải FIX ADV*
807
+ // R3 [MARK] (any|every|each|all) DEF (must|should|shall|needs to|has to|gets) [be] FIX ADV*
808
+ // R4 [MARK] bare-plural-DEF (must|should|shall|get) [be] FIX ADV*
809
+ // R5 [MARK] no DEF [luôn] [là (tiêu chí|nguyên tắc|quy tắc|quan điểm) [của tôi]] (nominal slogan)
810
+ // RC (R1|R2|R3|R4) và R6 (rule và purpose)
811
+ // R6 [phải] [tận root cause] để không (tái hiện|xảy ra|lặp lại) DEF nữa (purpose)
812
+ // F3 MARK [vẫn] là phải FIX ADV* (marker REQUIRED; no defect word, no scope word anywhere)
813
+ // F3p quan điểm của tôi [lần chạy này] vẫn là phải FIX ADV* (owner's exact opening)
814
+ // F4 fix [trên ukit] không phải chỉ để pass [thôi] [đâu] (negated purpose)
815
+ // F5 one fixed adverb phrase [nhé], or "nhé" alone ("ngay lập tức", "at its root cause", ...); reachable only after punctuation
816
+ // V1/V2/V3 three enumerated product-rationale sentences ("ukit là sản phẩm tôi sử dụng hỗ trợ rất nhiều sản phẩm khác" ...)
817
+ // ADV* is ONE closed whole-phrase adverb (SP_PHRASE: "ngay lập tức", "triệt để", "at its root cause", ...),
818
+ // optionally followed by "nhé"; never a run of loose words.
819
+ // ACCENTS ARE NEVER FOLDED BEFORE MATCHING. The grammar is written once, in canonical accented spelling; spw()
820
+ // compiles each Vietnamese word to an exact alternation of (its fully unaccented form | its ONE canonical
821
+ // spelling). So "lập" and "lắp"/"lấp"/"lặp", "để" and "đè"/"đẻ", "thấy" and "thay"/"thầy", "nữa" and "nửa" are
822
+ // different words: an accented token that is not the canonical spelling matches nothing. A token with no
823
+ // diacritic still stands for the canonical word (unaccented typing keeps working). English words are ASCII
824
+ // literals, so "FİXED" or "fíx" match nothing. SP_CANONICAL lists every accented word the grammar uses.
825
+ const SP_FOLD = (s) => s.normalize('NFD').replace(/[̀-ͯ]/g, '').replace(/đ/g, 'd');
826
+ const SP_ACCENTED = new Set();
827
+ const spw = (token) => {
828
+ const t = token.normalize('NFC');
829
+ const f = SP_FOLD(t);
830
+ if (f === t) return t;
831
+ SP_ACCENTED.add(t);
832
+ return `(?:${f}|${t})`;
833
+ };
834
+ const sp = (phrase) => phrase.trim().split(/\s+/).map(spw).join('\\s+');
835
+ const spAny = (...phrases) => `(?:${phrases.map(sp).join('|')})`;
836
+ const SP_DEF = `(?:bugs?|${sp('lỗi')}|defects?|crash(?:es)?|errors?|exceptions?|broken|regressions?|failures?|failing|fails?)`;
837
+ const SP_DEF_PLURAL = `(?:bugs|${sp('lỗi')}|defects|crashes|errors|exceptions|regressions|failures)`;
838
+ const SP_FIXV = `(?:fix|fixed|fixes|fixing|${sp('sửa')}|${sp('khắc phục')}|${sp('xử lý')}|resolved?)`;
839
+ // Adverbs are a closed list of whole PHRASES, never a run of words: one primary phrase, then optionally "nhé".
840
+ const SP_PHRASE = spAny('ngay lập tức', 'ngay luôn', 'ngay', 'luôn', 'triệt để', 'tận gốc', 'hoàn toàn', 'tận root cause', 'tận root cáue',
841
+ 'at its root cause', 'at the root cause', 'at its root', 'immediately', 'right away', 'at once', 'properly', 'fully', 'completely', 'thoroughly');
842
+ const SP_ADVRUN = `(?:\\s+${SP_PHRASE})?(?:\\s+${sp('nhé')})?`;
843
+ const SP_MARK = `(?:${spAny('luôn nhớ', 'luôn luôn', 'từ giờ', 'từ nay', 'nguyên tắc', 'tiêu chí', 'quy tắc', 'quan điểm',
844
+ 'always remember', 'from now on', 'as a rule', 'my rule is', 'my policy is', 'my principle is')})(?:\\s+${sp('của tôi')})?`;
845
+ const SP_MARK_PFX = `(?:${SP_MARK}\\s+)?`;
846
+ // The enumerated clause forms (see the header comment). Every one is anchored at both ends. Connector words
847
+ // (và ...) exist ONLY inside the compound form RC below; the clause splitter never consumes a word.
848
+ const SP_R1 = `${SP_MARK_PFX}${spAny('có', 'thấy', 'gặp', 'phát hiện')}\\s+${SP_DEF}\\s+${spAny('là', 'thì')}\\s+(?:${spAny('phải', 'luôn')}\\s+)?${SP_FIXV}${SP_ADVRUN}`;
849
+ const SP_R2 = `${SP_MARK_PFX}${sp('mọi')}\\s+${SP_DEF}\\s+(?:${sp('là')}\\s+|${sp('đều')}\\s+)?${sp('phải')}\\s+${SP_FIXV}${SP_ADVRUN}`;
850
+ const SP_R3 = `${SP_MARK_PFX}(?:any|every|each|all)\\s+${SP_DEF}\\s+(?:must|should|shall|needs? to|has to|gets?)\\s+(?:be\\s+)?${SP_FIXV}${SP_ADVRUN}`;
851
+ const SP_R4 = `${SP_MARK_PFX}${SP_DEF_PLURAL}\\s+(?:must|should|shall|get)\\s+(?:be\\s+)?${SP_FIXV}${SP_ADVRUN}`;
852
+ const SP_R6 = `(?:${sp('phải')}\\s+)?(?:${spAny('tận root cause', 'tận root cáue')}\\s+)?${sp('để không')}\\s+${spAny('tái hiện', 'xảy ra', 'lặp lại')}\\s+${SP_DEF}\\s+${sp('nữa')}`;
853
+ const SP_CLAUSE_FORMS = [
854
+ new RegExp(`^${SP_MARK}$`), // F1
855
+ new RegExp(`^${SP_R1}$`), // R1
856
+ new RegExp(`^${SP_R2}$`), // R2
857
+ new RegExp(`^${SP_R3}$`), // R3
858
+ new RegExp(`^${SP_R4}$`), // R4
859
+ new RegExp(`^${SP_MARK_PFX}no\\s+${SP_DEF}(?:\\s+${sp('luôn')})?(?:\\s+${sp('là')}\\s+${spAny('tiêu chí', 'nguyên tắc', 'quy tắc', 'quan điểm')}(?:\\s+${sp('của tôi')})?)?$`), // R5
860
+ new RegExp(`^(?:${SP_R1}|${SP_R2}|${SP_R3}|${SP_R4})\\s+${sp('và')}\\s+${SP_R6}$`), // RC: rule và purpose (owner's P2)
861
+ new RegExp(`^${SP_R6}$`), // R6
862
+ new RegExp(`^${SP_MARK}\\s+(?:${sp('vẫn')}\\s+)?${sp('là phải')}\\s+${SP_FIXV}${SP_ADVRUN}$`), // F3 (marker required)
863
+ new RegExp(`^${sp('quan điểm của tôi')}(?:\\s+${sp('lần chạy này')})?\\s+${sp('vẫn là phải')}\\s+${SP_FIXV}${SP_ADVRUN}$`), // F3p
864
+ new RegExp(`^fix(?:\\s+${sp('trên ukit')})?\\s+${sp('không phải chỉ để')}\\s+pass(?:\\s+${sp('thôi')})?(?:\\s+${sp('đâu')})?$`), // F4
865
+ new RegExp(`^(?:${SP_PHRASE}(?:\\s+${sp('nhé')})?|${sp('nhé')})$`), // F5 (reachable only after punctuation)
866
+ new RegExp(`^${sp('ukit là sản phẩm tôi sử dụng hỗ trợ rất nhiều sản phẩm khác')}$`), // V1
867
+ new RegExp(`^${sp('ukit là sản phẩm quan trọng')}$`), // V2
868
+ new RegExp(`^${sp('ukit hỗ trợ rất nhiều sản phẩm khác')}$`), // V3
869
+ ];
870
+ // Folded key -> canonical accented spelling(s). One spelling per word; a word with two legitimate tone
871
+ // placements would list both here and in the grammar.
872
+ const SP_CANONICAL = {};
873
+ for (const w of [...SP_ACCENTED].sort()) (SP_CANONICAL[SP_FOLD(w)] ||= []).push(w);
874
+ // The splitter splits on punctuation/newline ONLY. It must never contain a letter: a word consumed by a
875
+ // splitter is discarded unjudged. (Asserted by a test.)
876
+ const SP_CLAUSE_SPLIT = /[.!?;:\n,]+/;
877
+ // Forms that state a defect rule: at least one clause must be one of them (R1-R5 and RC).
878
+ const SP_RULE_FORM_COUNT = 7;
879
+ const STANDING_POLICY_MARKER = /\b(?:luon nho|luon luon|tu gio|tu nay|nguyen tac|tieu chi|quy tac|quan diem|always remember|from now on|as a rule|my (?:rule|policy|principle) is)\b/;
880
+ const STANDING_POLICY_CONCRETE = /[`"“”«»]|https?:\/\/|www\.|\b\w+\(\)|[\w.-]+\/[\w.-]+|\b[\w-]+\.(?:m?js|cjs|jsx?|tsx?|json|md|sh|py|ya?ml|css|html?|go|rs|java|rb|php|sql|toml|txt|lock|log)\b|\b[a-z]+[A-Z]\w*|\b\w+_\w+|\b\w*Error\b|\bE[A-Z]{3,}\b|\bv?\d+\.\d+|\bexit\s*(?:code|status)?\s*:?\s*-?\d+|\bstack\b|\b\d{3,}\b/;
881
+ const STANDING_POLICY_SYMPTOM = /\b(?:bi loi|khong chay|khong hoat dong|hong|treo|sai|van con|chua (?:duoc )?(?:fix|sua)|crash(?:es|ed)?|(?:does ?n[o']?t|won'?t|is ?n[o']?t) work|(?:is|are) broken|fail(?:s|ed|ing)?)\b/;
882
+ const STANDING_POLICY_DEICTIC_ANYWHERE = /\b(?:the above|above|vua roi|hien tai|current(?:ly)?|dang|failing|following|ben tren|o tren)\b/;
883
+ function isStandingPolicyPrompt(promptText = '') {
884
+ const raw = String(promptText ?? '').trim();
885
+ if (!raw || raw.length > 800 || STANDING_POLICY_CONCRETE.test(raw)) return false;
886
+ // The global rejects (marker present, no symptom, no deictic) are deliberately lenient and run on a folded
887
+ // copy; the clause forms below run on the RAW lowercase NFC text, where accents are exact. Nothing but
888
+ // Latin combining marks and "đ" is ever removed from the folded copy, and the raw text is what is judged.
889
+ const text = raw.toLowerCase().normalize('NFC').replace(/\s+/g, ' ');
890
+ const folded = SP_FOLD(text);
891
+ if (!STANDING_POLICY_MARKER.test(folded) || STANDING_POLICY_DEICTIC_ANYWHERE.test(folded) || STANDING_POLICY_SYMPTOM.test(folded)) return false;
892
+ const clauses = text.split(SP_CLAUSE_SPLIT);
893
+ let ruleClauses = 0;
894
+ for (const clause of clauses) {
895
+ const norm = clause.replace(/\s+/g, ' ').trim();
896
+ // Only a clause that is empty after whitespace/ASCII punctuation is skipped. Anything else (a letter or
897
+ // digit of any script, an emoji, a symbol) must match an enumerated form, else the prompt is not a policy.
898
+ if (!norm.replace(/[\s!-/:-@[-`{-~]/g, '')) continue;
899
+ const form = SP_CLAUSE_FORMS.findIndex((re) => re.test(norm));
900
+ if (form < 0) return false;
901
+ if (form >= 1 && form < SP_RULE_FORM_COUNT) ruleClauses += 1;
902
+ }
903
+ return ruleClauses > 0;
904
+ }
905
+
906
+ // A host-delivered peer (teammate/subagent/other-session) message: optional banner line, one or more CLOSED
907
+ // peer blocks, then nothing or (banner required) the host's own single-paragraph trailer, recognised by its
908
+ // stable lead words. Owner words anywhere else make it an owner prompt. A host wording change falls back to
909
+ // "not a peer prompt" (old routing), never to dropping owner text. Mirrors the early-exit check in skill-router.sh.
910
+ function isPeerMessagePrompt(promptText = '') {
911
+ const text = String(promptText ?? '').trim();
912
+ const banner = /^Another Claude session sent a message:[ \t]*\r?\n/i;
913
+ const bannered = banner.test(text);
914
+ let rest = text.replace(banner, '').trim();
915
+ const peerBlock = /^<(agent-message|teammate-message|cross-session-message)(?:\s[^>]*)?>[\s\S]*?<\/\1>\s*/;
916
+ let blocks = 0;
917
+ for (let m = peerBlock.exec(rest); m; m = peerBlock.exec(rest)) { rest = rest.slice(m[0].length); blocks += 1; }
918
+ const trailer = /^(?:This came from another Claude session|That .other Claude session. is an agent working inside this same session)[^\r\n]{0,1500}$/i;
919
+ return blocks > 0 && (rest === '' || (bannered && trailer.test(rest.trim())));
920
+ }
921
+
739
922
  function classifyOwnerControl(promptText = '') {
740
923
  const raw = String(promptText ?? '').normalize('NFC').trim();
924
+ // Text shape is never provenance here: an envelope-first/banner-first text already yields kind null because
925
+ // OWNER_STOP_EN/VI are anchored on the first lead (proved 0 diffs vs the former isPeerMessagePrompt guard).
741
926
  if (!raw || OWNER_CONTROL_HOOK_TEXT.test(raw)) return { kind: null };
742
927
  const stripped = raw.replace(/^[\s*#_-]+/, '');
743
928
  if (/^[>"'`\u201c\u2018]/.test(stripped)) return { kind: null };
@@ -929,7 +1114,13 @@ function classifySemanticCore({ promptText = '', targetFile = '' } = {}) {
929
1114
  const cronOperation = actionable.some((clause) => /\b(?:delete|remove|cancel|xoa|huy|ensure|dam bao)\b/.test(clause)
930
1115
  && /\bcron\b|scheduled\s+(?:cron\s+)?(?:task|job)|tac vu\s+(?:cron|dinh ky)/.test(clause))
931
1116
  && (!codeChangeVerb || hasOperationId);
1117
+ // Pure per clause and asked once by runtimeClause and once by gitClause for every clause; compute each clause once.
1118
+ const operationNotOrderedMemo = new Map();
932
1119
  const operationNotOrdered = (clause) => {
1120
+ if (!operationNotOrderedMemo.has(clause)) operationNotOrderedMemo.set(clause, operationNotOrderedUncached(clause));
1121
+ return operationNotOrderedMemo.get(clause);
1122
+ };
1123
+ const operationNotOrderedUncached = (clause) => {
933
1124
  const OP = '(?:restart|redeploy|deploy(?:ment)?|trien khai|khoi dong lai|git\\s+push|push\\s+(?:to\\s+)?origin|commit|push)';
934
1125
  const BAN = '(?:bi\\s+(?:cam|chan)|forbidden|prohibited|banned|not\\s+allowed|not\\s+permitted|disallowed)';
935
1126
  if (/\b(?:was|were|previously|before|formerly|no\s+longer|even\s+though|although|though|now\s+allows?|now\s+permits?|owner\s+allows?|khong\s+bi|da\s+duoc\s+phep|except)\b/.test(clause)) return false;
@@ -2964,6 +3155,8 @@ function applyTaskSemantics(contract, semantic) {
2964
3155
  }
2965
3156
 
2966
3157
  function hasAdvisoryOnlyAssertion({ promptText = '', commandText = '' } = {}) {
3158
+ // A standing owner policy about bugs in general is advisory: no defect is named, nothing to repro.
3159
+ if (!String(commandText || '').trim() && isStandingPolicyPrompt(promptText)) return true;
2967
3160
  const folded = `${promptText ?? ''}\n${commandText ?? ''}`
2968
3161
  .toLowerCase()
2969
3162
  .normalize('NFD')
@@ -4486,7 +4679,36 @@ function applyTaskSemantics(contract, semantic) {
4486
4679
  }
4487
4680
  }
4488
4681
  let expectedRouteVersion;
4682
+ // Set only while a fresh owner prompt over an armed contract has not yet published (see the gate before
4683
+ // promptText); cleared once the provisional publication commits. Null = a kill behaves as before.
4684
+ let deadlineMarkerGate = null;
4685
+ deadlineHandler = async () => {
4686
+ const gate = deadlineMarkerGate;
4687
+ if (!gate || !sessionRoutePath) return;
4688
+ const lockModule = path.join(process.env.HOOK_DIR || path.join(projectRoot, '.claude', 'hooks'), '..', 'ukit', 'runtime', 'async-lock.mjs');
4689
+ const { withAsyncLock } = await import(pathToFileURL(lockModule).href);
4690
+ await withAsyncLock(sessionRoutePath, { deadlineMs: 300 }, async () => {
4691
+ // Same compare as persistRouteState: skip when the session route moved since this hook read it.
4692
+ // Compare against the version captured at gate time (never a fresh read, never the live
4693
+ // expectedRouteVersion that a committing publication advances): another process that published
4694
+ // since the gate, or our own publication having committed, makes this a skip.
4695
+ const bytes = await readRouteVersion();
4696
+ if (bytes !== gate.routeVersion || deadlineMarkerGate !== gate) return;
4697
+ let committedStop = null;
4698
+ try {
4699
+ const committed = bytes === null ? null : JSON.parse(bytes);
4700
+ if (committed?.ownerControl?.kind === 'stop' && committed.sessionId === sessionId) committedStop = committed.ownerControl;
4701
+ } catch {}
4702
+ await writeJsonFileAtomic(sessionRoutePath, JSON.stringify({
4703
+ sessionId, taskInstanceId: gate.taskInstanceId, routeGeneration: gate.routeGeneration,
4704
+ routePersistenceRevision: crypto.randomUUID(), routePublicationIncomplete: true,
4705
+ ...(committedStop ? { ownerControl: committedStop } : {}),
4706
+ }));
4707
+ });
4708
+ };
4489
4709
  async function persistRouteState(text, recoveryOwner = null) {
4710
+ // After the deadline fired the only permitted write is the kill marker above.
4711
+ if (deadlineReached) throw new Error('hook deadline reached before route publication');
4490
4712
  if (sessionId) {
4491
4713
  // The lock primitive ships beside this hook; resolve it from the hook's own install dir so a
4492
4714
  // workspace whose runtime copy is absent/partial still takes the same lock (never unlocked).
@@ -4505,6 +4727,7 @@ function applyTaskSemantics(contract, semantic) {
4505
4727
  } else if (!handoffSkill && !handoffExpansion && await readRouteVersion() !== expectedRouteVersion) {
4506
4728
  throw new Error('session route changed before write');
4507
4729
  }
4730
+ if (deadlineReached) throw new Error('hook deadline reached before route publication');
4508
4731
  const persisted = await persistRouteStateLocked(text);
4509
4732
  expectedRouteVersion = await readRouteVersion();
4510
4733
  return persisted;
@@ -4606,6 +4829,7 @@ function applyTaskSemantics(contract, semantic) {
4606
4829
  const informationalTurn = !continuingTask && !semantic.statusReport
4607
4830
  && (semantic.taskKind === 'CODE_IMPLEMENTATION' || answerQuestion)
4608
4831
  && (isInformationalPrompt({ promptText: turnPrompt })
4832
+ || isStandingPolicyPrompt(turnPrompt)
4609
4833
  || isPureGreetingPrompt({ promptText: turnPrompt }));
4610
4834
  // A system-injected turn (wakeup / compaction summary) resumes the previous task; when that task holds
4611
4835
  // no contract (the owner's last turn was a question), the injected wording must not mint one: it was
@@ -4742,6 +4966,10 @@ function applyTaskSemantics(contract, semantic) {
4742
4966
  } catch { return null; }
4743
4967
  })();
4744
4968
  const markerControl = persisted.ownerControl ?? committedStop;
4969
+ // Re-check under the sidecar lock, right before the first write: if the kill marker already landed (or the
4970
+ // deadline fired) this publication must abort, never overwrite the marker. A publication that passed this
4971
+ // point has written its own pending marker first, so a hard exit mid-way still fails closed.
4972
+ if (deadlineReached) throw new Error('hook deadline reached before route publication');
4745
4973
  if (sessionId) await writeJsonFileAtomic(sessionRoutePath, JSON.stringify({ sessionId, taskInstanceId, routeGeneration: persisted.routeGeneration, routePersistenceRevision: persisted.routePersistenceRevision, routePublicationIncomplete: true, ...(markerControl ? { ownerControl: markerControl } : {}) }));
4746
4974
  try {
4747
4975
  await writeJsonFileAtomic(statePath, text);
@@ -5009,6 +5237,26 @@ function applyTaskSemantics(contract, semantic) {
5009
5237
  coordinationTurn = true;
5010
5238
  return false;
5011
5239
  }
5240
+ // Idle-session peer delivery (real host shape, host 2.1.322): queue-operation enqueue + dequeue (no
5241
+ // content/origin) then ONE meta user entry stamped origin.kind 'peer' / turnOrigin 'peer' /
5242
+ // promptSource 'system'. The hook payload prompt is the bare envelope block; the transcript entry
5243
+ // holds the host's banner line + block + one-paragraph trailer. The branch requires the same
5244
+ // session, the current turn (the assistant boundary above already cleared deliveryCurrent), the
5245
+ // prompt occurring exactly once in the entry text, only the known banner line (or nothing) before
5246
+ // it, and only a known single-line trailer (or nothing) after it. Any other extra text is not
5247
+ // proof. A human paste leaves origin.kind 'human' / promptSource 'typed' and never matches.
5248
+ if (deliveryCurrent && entry.isMeta === true && entry.promptSource === 'system' && entry.turnOrigin === 'peer'
5249
+ && entry.origin?.kind === 'peer' && sessionId && entry.sessionId === sessionId) {
5250
+ const at = text.indexOf(promptTrim);
5251
+ const before = at < 0 ? null : text.slice(0, at).trim();
5252
+ const after = at < 0 ? null : text.slice(at + promptTrim.length).trim();
5253
+ if (at >= 0 && text.indexOf(promptTrim, at + 1) < 0
5254
+ && (before === '' || before === 'Another Claude session sent a message:')
5255
+ && (after === '' || (!after.includes('\n') && /^(?:This came from another Claude session|That "other Claude session" is an agent)\b/.test(after)))) {
5256
+ coordinationTurn = true;
5257
+ return false;
5258
+ }
5259
+ }
5012
5260
  if (entry.isMeta === true && entry.turnOrigin === 'scheduled'
5013
5261
  && entry.promptSource === 'system' && entry.scheduledTaskId
5014
5262
  && entry.sessionId === sessionId && text === promptTrim
@@ -5016,6 +5264,9 @@ function applyTaskSemantics(contract, semantic) {
5016
5264
  coordinationTurn = true;
5017
5265
  return false;
5018
5266
  }
5267
+ // A peer-stamped record is delivery proof only inside this session; another session's record
5268
+ // (or a stale one) never exempts this prompt.
5269
+ if (entry.turnOrigin === 'peer' || entry.origin?.kind === 'peer') return false;
5019
5270
  return entry.isMeta === true && (entry.turnOrigin === 'scheduled' || entry.promptSource === 'system')
5020
5271
  && text === promptTrim;
5021
5272
  }
@@ -5427,6 +5678,14 @@ function applyTaskSemantics(contract, semantic) {
5427
5678
  : String(transcriptPathCandidate).trim() || null;
5428
5679
 
5429
5680
  const promptText = extractPrompt(payload);
5681
+ // Kill-marker gate: a fresh owner prompt (not a tool event, continuation, system turn, guidance or
5682
+ // handoff-bound task) over an armed previous contract. Past this point only the provisional publication
5683
+ // can replace that contract; a deadline kill before it commits must not leave the old contract live.
5684
+ if (!payload.tool_name && sessionId && promptText && !continuingTask && !systemOriginTurn && !guidanceTurn
5685
+ && !handoffExpansion && !handoffSkill && !previous.handoffRunId && previous.taskInstanceId && expectedRouteVersion !== undefined
5686
+ && previous.routeSummary?.executionContract?.completionEvidence?.length) {
5687
+ deadlineMarkerGate = { taskInstanceId: previous.taskInstanceId, routeGeneration: previous.routeGeneration || previous.taskInstanceId, routeVersion: expectedRouteVersion };
5688
+ }
5430
5689
  const commandText = payload.tool_input?.command || payload.command || '';
5431
5690
  const filePath = normalizeRelativeFile(projectRoot, payload.tool_input?.file_path || payload.file_path || '');
5432
5691
  const { buildRouteSignalText } = await loadLanguageTools(projectRoot);
@@ -5520,6 +5779,11 @@ function applyTaskSemantics(contract, semantic) {
5520
5779
  && !filePath;
5521
5780
 
5522
5781
  if (active.length === 0 || informationalNoTargetPrompt) {
5782
+ // This branch deliberately carries the previous contract forward (see the persist below), so a kill here
5783
+ // must not strand a marker that drops it. deliveryOnlyNoRoute drops the contract on its normal write, so the
5784
+ // gate stays armed there. With the gate null the deadline handler returns at once and the process exits in
5785
+ // the same microtask drain, before any pending import (the advisory below) can resume and print.
5786
+ if (previous?.routeSummary && !deliveryOnlyNoRoute) deadlineMarkerGate = null;
5523
5787
  const lastExplicitUserPromptText = promptText.trim()
5524
5788
  || previous?.routingContext?.lastExplicitUserPromptText
5525
5789
  || '';
@@ -5714,6 +5978,7 @@ function applyTaskSemantics(contract, semantic) {
5714
5978
  provisionalState.fingerprint = buildRouteStateFingerprint(provisionalState);
5715
5979
  await ensureDir(statePath);
5716
5980
  await persistRouteState(JSON.stringify(provisionalState));
5981
+ deadlineMarkerGate = null;
5717
5982
 
5718
5983
  let cacheUtils = null;
5719
5984
  if (await pathExists(cacheUtilsPath)) {
@@ -5970,6 +6235,9 @@ function applyTaskSemantics(contract, semantic) {
5970
6235
  process.stdout.write(`[ukit-skill-router] Helper: ${routeSummary.helperHint}\n`);
5971
6236
  }
5972
6237
  })().catch((error) => {
6238
+ // Once the self-deadline fired, only the deadline timer's own path (marker write, then exit; or the 400 ms
6239
+ // hard exit) may end the process or write to stdout: a refused publication here is the deadline, not a crash.
6240
+ if (deadlineReached) return;
5973
6241
  const detail = error?.message || String(error);
5974
6242
  process.stderr.write(`[ukit-skill-router] ${detail}\n`);
5975
6243
  // BUG-C23-07: a crashed router abandons configured routing work — announce the
@@ -87,9 +87,9 @@ With both the philosophy and the conceptual framework established, express it on
87
87
 
88
88
  To create museum or magazine quality work, use the design philosophy as the foundation. Create one single page, highly visual, design-forward PDF or PNG output (unless asked for more pages). Generally use repeating patterns and perfect shapes. Treat the abstract philosophical design as if it were a scientific bible, borrowing the visual language of systematic observation—dense accumulation of marks, repeated elements, or layered patterns that build meaning through patient repetition and reward sustained viewing. Add sparse, clinical typography and systematic reference markers that suggest this could be a diagram from an imaginary discipline, treating the invisible subject with the same reverence typically reserved for documenting observable phenomena. Anchor the piece with simple phrase(s) or details positioned subtly, using a limited color palette that feels intentional and cohesive. Embrace the paradox of using analytical visual language to express ideas about human experience: the result should feel like an artifact that proves something ephemeral can be studied, mapped, and understood through careful attention. This is true art.
89
89
 
90
- **Text as a contextual element**: Text is always minimal and visual-first, but let context guide whether that means whisper-quiet labels or bold typographic gestures. A punk venue poster might have larger, more aggressive type than a minimalist ceramics studio identity. Most of the time, font should be thin. All use of fonts must be design-forward and prioritize visual communication. Regardless of text scale, nothing falls off the page and nothing overlaps. Every element must be contained within the canvas boundaries with proper margins. Check carefully that all text, graphics, and visual elements have breathing room and clear separation. This is non-negotiable for professional execution. **IMPORTANT: Use different fonts if writing text. Start with the curated built-in font set in `./canvas-fonts` (sans, serif, mono, display, script). Only widen beyond that when the task truly needs it. Regardless of approach, sophistication is non-negotiable.**
90
+ **Text as a contextual element**: Text is always minimal and visual-first, but let context guide whether that means whisper-quiet labels or bold typographic gestures. A punk venue poster might have larger, more aggressive type than a minimalist ceramics studio identity. Most of the time, font should be thin. All use of fonts must be design-forward and prioritize visual communication. Regardless of text scale, nothing falls off the page and nothing overlaps. Every element must be contained within the canvas boundaries with proper margins. Check carefully that all text, graphics, and visual elements have breathing room and clear separation. This is non-negotiable for professional execution. **IMPORTANT: Use different fonts if writing text. Start with the curated built-in font set in `./canvas-fonts`: Outfit (sans), Instrument Serif (serif), JetBrains Mono (mono), Tektur (display), Nothing You Could Do (script). Only widen beyond that when the task truly needs it: more faces (Bricolage Grotesque, Instrument Sans, Lora, Young Serif, plus bold/italic variable files) can be downloaded with `node ./scripts/fetch-fonts.mjs --list` / `node ./scripts/fetch-fonts.mjs <Family>` when the network is available. Regardless of approach, sophistication is non-negotiable.**
91
91
 
92
- Prefer the bundled curated font set first so the skill stays fast, portable, and production-friendly after a simple install. Get creative by making the typography actually part of the art itself -- if the art is abstract, bring the font onto the canvas, not typeset digitally.
92
+ Prefer the bundled curated font set first so the skill stays fast, portable, and production-friendly after a simple install; if the network is unavailable, stay with the bundled faces. Get creative by making the typography actually part of the art itself -- if the art is abstract, bring the font onto the canvas, not typeset digitally.
93
93
 
94
94
  To push boundaries, follow design instinct/intuition while using the philosophy as a guiding principle. Embrace ultimate design freedom and choice. Push aesthetics and design to the frontier.
95
95
 
@@ -1,8 +1,8 @@
1
- Copyright 2022 The Instrument Sans Project Authors (https://github.com/Instrument/instrument-sans)
1
+ Copyright 2022 The Instrument Serif Project Authors (https://github.com/Instrument/instrument-serif)
2
2
 
3
3
  This Font Software is licensed under the SIL Open Font License, Version 1.1.
4
4
  This license is copied below, and is also available with a FAQ at:
5
- https://openfontlicense.org
5
+ https://scripts.sil.org/OFL
6
6
 
7
7
 
8
8
  -----------------------------------------------------------
@@ -18,7 +18,7 @@ with others.
18
18
 
19
19
  The OFL allows the licensed fonts to be used, studied, modified and
20
20
  redistributed freely as long as they are not sold by themselves. The
21
- fonts, including any derivative works, can be bundled, embedded,
21
+ fonts, including any derivative works, can be bundled, embedded,
22
22
  redistributed and/or sold with any software provided that any reserved
23
23
  names are not used by derivative works. The fonts and derivatives,
24
24
  however, cannot be released under any other type of license. The
@@ -0,0 +1,148 @@
1
+ #!/usr/bin/env node
2
+ // Fetch optional canvas-design fonts on demand (dependency-free, OFL fonts only).
3
+ // Usage: node fetch-fonts.mjs --list | --all | <Family> [<Family> ...]
4
+ // Source: google/fonts at a pinned commit (immutable raw URLs). Every file is
5
+ // SHA-256 verified before it is written into ../canvas-fonts/.
6
+ import { createHash } from 'node:crypto';
7
+ import { mkdir, rename, writeFile, access, unlink } from 'node:fs/promises';
8
+ import path from 'node:path';
9
+ import { fileURLToPath } from 'node:url';
10
+
11
+ export const PINNED_SHA = 'cc39c4c2c304bc368c9b7c311ea2bcc6013299fe';
12
+ export const REQUEST_TIMEOUT_MS = 30_000;
13
+ const RAW = `https://raw.githubusercontent.com/google/fonts/${PINNED_SHA}/ofl`;
14
+
15
+ const url = (dir, file) =>
16
+ `${RAW}/${dir}/${file.replace(/\[/g, '%5B').replace(/\]/g, '%5D').replace(/,/g, '%2C')}`;
17
+
18
+ // local = file name written into canvas-fonts/. Variable fonts cover all weights.
19
+ const FAMILIES = {
20
+ BricolageGrotesque: {
21
+ dir: 'bricolagegrotesque',
22
+ licenseSha256: '4b5a7d8f37f5602621c8a8d7358a6a2e71317e6c231c661e15aef0275d3e07ba',
23
+ files: [{ local: 'BricolageGrotesque-Variable.ttf', remote: 'BricolageGrotesque[opsz,wdth,wght].ttf', sha256: '413e7357809ddd12fd80a96a8a396de0e401638d4acd3cb3e37532f0472ac682' }],
24
+ },
25
+ InstrumentSans: {
26
+ dir: 'instrumentsans',
27
+ licenseSha256: '9e27a72ed30eb49a08678f6a5d6ed98ec7ba5368f541637ee0683ec9134ef966',
28
+ files: [
29
+ { local: 'InstrumentSans-Variable.ttf', remote: 'InstrumentSans[wdth,wght].ttf', sha256: 'b24f1812584816958afcf22e22d08e44318c5e51651e25d2438efdde389b33b1' },
30
+ { local: 'InstrumentSans-Italic-Variable.ttf', remote: 'InstrumentSans-Italic[wdth,wght].ttf', sha256: 'a74203cc5066a3b2f8de1a7b0887ef897773c2319dc86c911f8e85350cde0d07' },
31
+ ],
32
+ },
33
+ InstrumentSerif: {
34
+ dir: 'instrumentserif',
35
+ licenseSha256: '129ed7618959716959f2941fdd5b49e0ad6e6c1d78726761786a00253d865521',
36
+ files: [{ local: 'InstrumentSerif-Italic.ttf', remote: 'InstrumentSerif-Italic.ttf', sha256: '08939b8bdf534afec24ae0ef5e03f948940cd9a8fe08e7fecbad040e62327385' }],
37
+ },
38
+ JetBrainsMono: {
39
+ dir: 'jetbrainsmono',
40
+ licenseSha256: 'b2fe5e8987594e9ffd1d2ca52a2f5d73eb8335243893c5d6254b5ad69269591d',
41
+ files: [
42
+ { local: 'JetBrainsMono-Variable.ttf', remote: 'JetBrainsMono[wght].ttf', sha256: '48715a42ec242c21e9f02692891e147d022299a52e48d5e413e1a942193ffeda' },
43
+ { local: 'JetBrainsMono-Italic-Variable.ttf', remote: 'JetBrainsMono-Italic[wght].ttf', sha256: '85ae2a5cd3f56baf1ce1c21a851322c58e3d8fbe8e8ad4a4d090a820dd7fe558' },
44
+ ],
45
+ },
46
+ Lora: {
47
+ dir: 'lora',
48
+ licenseSha256: '1d9a970809ac804b582a6ce7f0ebc4e7fefcbfd7ff6299cad35ee656a21be716',
49
+ files: [
50
+ { local: 'Lora-Variable.ttf', remote: 'Lora[wght].ttf', sha256: '822a6621ccbe8d97d20ac88c1c41f5615c9c2c202eaa75f272cd452aac6475a7' },
51
+ { local: 'Lora-Italic-Variable.ttf', remote: 'Lora-Italic[wght].ttf', sha256: '22d8d8854b53807aa664ca34f2031a9ed57a1d0dea296b8b96cdd3aad937a2b3' },
52
+ ],
53
+ },
54
+ Outfit: {
55
+ dir: 'outfit',
56
+ licenseSha256: 'c676351bf8576b9aba743cd5eaa8c0e7ee0d51f805d720447b4df4ddb6a2e416',
57
+ files: [{ local: 'Outfit-Variable.ttf', remote: 'Outfit[wght].ttf', sha256: 'fc7287273e66929776e2ba54f144fe699080bec29f61bf649d70d871468aeade' }],
58
+ },
59
+ Tektur: {
60
+ dir: 'tektur',
61
+ licenseSha256: 'ff4bb37f716836feb5038e1bf5c47e5a1946717fcfabb175086ed49f85ea47fd',
62
+ files: [{ local: 'Tektur-Variable.ttf', remote: 'Tektur[wdth,wght].ttf', sha256: 'a4c451e5336874811267c2a514efa09bca7bc8cabf32a310f0b44e111eacb933' }],
63
+ },
64
+ YoungSerif: {
65
+ dir: 'youngserif',
66
+ licenseSha256: '737d8d343b674c6894f373de71a044b6782c130f2aebf180933d63ddf7a3dc19',
67
+ files: [{ local: 'YoungSerif-Regular.ttf', remote: 'YoungSerif-Regular.ttf', sha256: '42bb2602364b28569fdce5eeb6ab3d81cf8090ba81b211f1229ed69f33155523' }],
68
+ },
69
+ };
70
+
71
+ /** Flat manifest: [{ family, local, url, sha256, license }] */
72
+ export function buildManifest() {
73
+ const out = [];
74
+ for (const [family, def] of Object.entries(FAMILIES)) {
75
+ for (const f of def.files) {
76
+ out.push({ family, local: f.local, url: url(def.dir, f.remote), sha256: f.sha256, license: false });
77
+ }
78
+ out.push({ family, local: `${family}-OFL.txt`, url: url(def.dir, 'OFL.txt'), sha256: def.licenseSha256, license: true });
79
+ }
80
+ return out;
81
+ }
82
+
83
+ export function familyNames() {
84
+ return Object.keys(FAMILIES);
85
+ }
86
+
87
+ /** Resolve a local name inside fontsDir; throws if it would escape. */
88
+ export function safeTarget(fontsDir, local) {
89
+ const root = path.resolve(fontsDir);
90
+ const target = path.resolve(root, local);
91
+ if (path.dirname(target) !== root || local !== path.basename(local)) {
92
+ throw new Error(`refusing to write outside canvas-fonts: ${local}`);
93
+ }
94
+ return target;
95
+ }
96
+
97
+ async function download(u) {
98
+ const res = await fetch(u, { signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS), redirect: 'follow' });
99
+ if (!res.ok) throw new Error(`HTTP ${res.status} for ${u}`);
100
+ return Buffer.from(await res.arrayBuffer());
101
+ }
102
+
103
+ async function exists(p) {
104
+ try { await access(p); return true; } catch { return false; }
105
+ }
106
+
107
+ async function main(argv) {
108
+ const here = path.dirname(fileURLToPath(import.meta.url));
109
+ const fontsDir = path.resolve(here, '..', 'canvas-fonts');
110
+ const names = familyNames();
111
+ if (argv.includes('--list') || argv.length === 0) {
112
+ console.log('Available families (OFL, google/fonts @ ' + PINNED_SHA.slice(0, 12) + '):\n ' + names.join('\n '));
113
+ console.log('\nUsage: node fetch-fonts.mjs <Family...> | --all');
114
+ return 0;
115
+ }
116
+ const wanted = argv.includes('--all') ? names : argv;
117
+ const unknown = wanted.filter((n) => !names.includes(n));
118
+ if (unknown.length) {
119
+ console.error(`Unknown family: ${unknown.join(', ')}. Use --list.`);
120
+ return 1;
121
+ }
122
+ await mkdir(fontsDir, { recursive: true });
123
+ for (const entry of buildManifest().filter((e) => wanted.includes(e.family))) {
124
+ const target = safeTarget(fontsDir, entry.local);
125
+ // Keep an already bundled licence file; it is the same OFL family text.
126
+ if (entry.license && (await exists(target))) continue;
127
+ const data = await download(entry.url);
128
+ const got = createHash('sha256').update(data).digest('hex');
129
+ if (got !== entry.sha256) throw new Error(`SHA-256 mismatch for ${entry.local}: expected ${entry.sha256}, got ${got}`);
130
+ const tmp = `${target}.${process.pid}.tmp`;
131
+ try {
132
+ await writeFile(tmp, data);
133
+ await rename(tmp, target);
134
+ } catch (err) {
135
+ await unlink(tmp).catch(() => {});
136
+ throw err;
137
+ }
138
+ console.log(`fetched ${entry.local}`);
139
+ }
140
+ return 0;
141
+ }
142
+
143
+ if (process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {
144
+ main(process.argv.slice(2)).then(
145
+ (code) => process.exit(code),
146
+ (err) => { console.error(`fetch-fonts failed: ${err.message}`); process.exit(1); },
147
+ );
148
+ }
@@ -0,0 +1,26 @@
1
+ #!/usr/bin/env node
2
+ // Explicit, opt-in step: embed one short descriptor per indexed file through UKIT_INDEX_EMBED_URL
3
+ // (OpenAI-compatible /v1/embeddings). PRIVACY: this sends file text (path, symbol names, leading
4
+ // comment; at most ~240 characters per file) to that endpoint. Never part of index build/refresh
5
+ // and never run from a hook. Usage: node .claude/ukit/index/embed-index.mjs [--dims N] [--root DIR]
6
+ import path from 'node:path';
7
+ import { buildSemanticVectors, embedConfig } from './lib/semantic-lane.mjs';
8
+
9
+ const args = process.argv.slice(2);
10
+ const flag = (name, fallback) => {
11
+ const i = args.indexOf(name);
12
+ return i >= 0 && args[i + 1] ? args[i + 1] : fallback;
13
+ };
14
+ try {
15
+ const cfg = embedConfig();
16
+ if (cfg) console.log(`[ukit:index:embed] sending file descriptors (path, symbols, leading comment) to ${new URL(cfg.url).host}`);
17
+ const started = Date.now();
18
+ const result = await buildSemanticVectors({
19
+ rootDir: path.resolve(flag('--root', process.cwd())),
20
+ dims: Number.parseInt(flag('--dims', '0'), 10) || 0,
21
+ });
22
+ console.log(`[ukit:index:embed] ${result.embedded} embedded, ${result.reused} reused, ${result.files} files, dims=${result.dims}, ${result.bytes} bytes, ${Date.now() - started} ms`);
23
+ } catch (error) {
24
+ console.error(`[ukit:index:embed] ${error && error.message ? error.message : error}`);
25
+ process.exitCode = 1;
26
+ }