minimal-vibe-coding-kit 0.4.2 → 0.5.1

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 (163) hide show
  1. package/.agents/skills/claim/SKILL.md +82 -0
  2. package/.agents/skills/tutien/SKILL.md +97 -0
  3. package/.agents/skills/tutien/references/adaptive-response.md +68 -0
  4. package/.agents/skills/tutien/references/classification.md +64 -0
  5. package/.agents/skills/tutien/references/lore-sources.md +43 -0
  6. package/.agents/skills/tutien/references/privacy.md +45 -0
  7. package/.agents/skills/tutien/references/schema.md +106 -0
  8. package/.agents/skills/tutien/references/scoring-and-realms.md +37 -0
  9. package/.agents/skills/tutien/references/story-system.md +176 -0
  10. package/.agents/skills/tutien/references/vi-style-guide.md +89 -0
  11. package/.agents/skills/tutien/references/voice-and-mode.md +59 -0
  12. package/.agents/skills/tutien/scripts/adapters/generic-jsonl.mjs +82 -0
  13. package/.agents/skills/tutien/scripts/adapters/git.mjs +48 -0
  14. package/.agents/skills/tutien/scripts/adapters/plain-transcript.mjs +37 -0
  15. package/.agents/skills/tutien/scripts/analyze-history.mjs +84 -0
  16. package/.agents/skills/tutien/scripts/catalog.mjs +130 -0
  17. package/.agents/skills/tutien/scripts/classify.mjs +338 -0
  18. package/.agents/skills/tutien/scripts/command.mjs +126 -0
  19. package/.agents/skills/tutien/scripts/compare.mjs +41 -0
  20. package/.agents/skills/tutien/scripts/metrics.mjs +306 -0
  21. package/.agents/skills/tutien/scripts/normalize-events.mjs +68 -0
  22. package/.agents/skills/tutien/scripts/project-profile.mjs +202 -0
  23. package/.agents/skills/tutien/scripts/redact.mjs +30 -0
  24. package/.agents/skills/tutien/scripts/render-report.mjs +479 -0
  25. package/.agents/skills/tutien/scripts/response-brief.mjs +103 -0
  26. package/.agents/skills/tutien/scripts/run-tutien.mjs +350 -0
  27. package/.agents/skills/tutien/scripts/score.mjs +97 -0
  28. package/.agents/skills/tutien/scripts/snapshot.mjs +76 -0
  29. package/.agents/skills/tutien/scripts/story-ledger.mjs +241 -0
  30. package/.agents/skills/tutien/scripts/villains.mjs +196 -0
  31. package/.claude/skills/claim/SKILL.md +82 -0
  32. package/.claude/skills/tutien/SKILL.md +97 -0
  33. package/.claude/skills/tutien/references/adaptive-response.md +68 -0
  34. package/.claude/skills/tutien/references/classification.md +64 -0
  35. package/.claude/skills/tutien/references/lore-sources.md +43 -0
  36. package/.claude/skills/tutien/references/privacy.md +45 -0
  37. package/.claude/skills/tutien/references/schema.md +106 -0
  38. package/.claude/skills/tutien/references/scoring-and-realms.md +37 -0
  39. package/.claude/skills/tutien/references/story-system.md +176 -0
  40. package/.claude/skills/tutien/references/vi-style-guide.md +89 -0
  41. package/.claude/skills/tutien/references/voice-and-mode.md +59 -0
  42. package/.claude/skills/tutien/scripts/adapters/generic-jsonl.mjs +82 -0
  43. package/.claude/skills/tutien/scripts/adapters/git.mjs +48 -0
  44. package/.claude/skills/tutien/scripts/adapters/plain-transcript.mjs +37 -0
  45. package/.claude/skills/tutien/scripts/analyze-history.mjs +84 -0
  46. package/.claude/skills/tutien/scripts/catalog.mjs +130 -0
  47. package/.claude/skills/tutien/scripts/classify.mjs +338 -0
  48. package/.claude/skills/tutien/scripts/command.mjs +126 -0
  49. package/.claude/skills/tutien/scripts/compare.mjs +41 -0
  50. package/.claude/skills/tutien/scripts/metrics.mjs +306 -0
  51. package/.claude/skills/tutien/scripts/normalize-events.mjs +68 -0
  52. package/.claude/skills/tutien/scripts/project-profile.mjs +202 -0
  53. package/.claude/skills/tutien/scripts/redact.mjs +30 -0
  54. package/.claude/skills/tutien/scripts/render-report.mjs +479 -0
  55. package/.claude/skills/tutien/scripts/response-brief.mjs +103 -0
  56. package/.claude/skills/tutien/scripts/run-tutien.mjs +350 -0
  57. package/.claude/skills/tutien/scripts/score.mjs +97 -0
  58. package/.claude/skills/tutien/scripts/snapshot.mjs +76 -0
  59. package/.claude/skills/tutien/scripts/story-ledger.mjs +241 -0
  60. package/.claude/skills/tutien/scripts/villains.mjs +196 -0
  61. package/.codex-plugin/plugin.json +1 -1
  62. package/.cursor/skills/claim/SKILL.md +82 -0
  63. package/.cursor/skills/tutien/SKILL.md +97 -0
  64. package/.cursor/skills/tutien/references/adaptive-response.md +68 -0
  65. package/.cursor/skills/tutien/references/classification.md +64 -0
  66. package/.cursor/skills/tutien/references/lore-sources.md +43 -0
  67. package/.cursor/skills/tutien/references/privacy.md +45 -0
  68. package/.cursor/skills/tutien/references/schema.md +106 -0
  69. package/.cursor/skills/tutien/references/scoring-and-realms.md +37 -0
  70. package/.cursor/skills/tutien/references/story-system.md +176 -0
  71. package/.cursor/skills/tutien/references/vi-style-guide.md +89 -0
  72. package/.cursor/skills/tutien/references/voice-and-mode.md +59 -0
  73. package/.cursor/skills/tutien/scripts/adapters/generic-jsonl.mjs +82 -0
  74. package/.cursor/skills/tutien/scripts/adapters/git.mjs +48 -0
  75. package/.cursor/skills/tutien/scripts/adapters/plain-transcript.mjs +37 -0
  76. package/.cursor/skills/tutien/scripts/analyze-history.mjs +84 -0
  77. package/.cursor/skills/tutien/scripts/catalog.mjs +130 -0
  78. package/.cursor/skills/tutien/scripts/classify.mjs +338 -0
  79. package/.cursor/skills/tutien/scripts/command.mjs +126 -0
  80. package/.cursor/skills/tutien/scripts/compare.mjs +41 -0
  81. package/.cursor/skills/tutien/scripts/metrics.mjs +306 -0
  82. package/.cursor/skills/tutien/scripts/normalize-events.mjs +68 -0
  83. package/.cursor/skills/tutien/scripts/project-profile.mjs +202 -0
  84. package/.cursor/skills/tutien/scripts/redact.mjs +30 -0
  85. package/.cursor/skills/tutien/scripts/render-report.mjs +479 -0
  86. package/.cursor/skills/tutien/scripts/response-brief.mjs +103 -0
  87. package/.cursor/skills/tutien/scripts/run-tutien.mjs +350 -0
  88. package/.cursor/skills/tutien/scripts/score.mjs +97 -0
  89. package/.cursor/skills/tutien/scripts/snapshot.mjs +76 -0
  90. package/.cursor/skills/tutien/scripts/story-ledger.mjs +241 -0
  91. package/.cursor/skills/tutien/scripts/villains.mjs +196 -0
  92. package/.grok/skills/claim/SKILL.md +82 -0
  93. package/.grok/skills/tutien/SKILL.md +97 -0
  94. package/.grok/skills/tutien/references/adaptive-response.md +68 -0
  95. package/.grok/skills/tutien/references/classification.md +64 -0
  96. package/.grok/skills/tutien/references/lore-sources.md +43 -0
  97. package/.grok/skills/tutien/references/privacy.md +45 -0
  98. package/.grok/skills/tutien/references/schema.md +106 -0
  99. package/.grok/skills/tutien/references/scoring-and-realms.md +37 -0
  100. package/.grok/skills/tutien/references/story-system.md +176 -0
  101. package/.grok/skills/tutien/references/vi-style-guide.md +89 -0
  102. package/.grok/skills/tutien/references/voice-and-mode.md +59 -0
  103. package/.grok/skills/tutien/scripts/adapters/generic-jsonl.mjs +82 -0
  104. package/.grok/skills/tutien/scripts/adapters/git.mjs +48 -0
  105. package/.grok/skills/tutien/scripts/adapters/plain-transcript.mjs +37 -0
  106. package/.grok/skills/tutien/scripts/analyze-history.mjs +84 -0
  107. package/.grok/skills/tutien/scripts/catalog.mjs +130 -0
  108. package/.grok/skills/tutien/scripts/classify.mjs +338 -0
  109. package/.grok/skills/tutien/scripts/command.mjs +126 -0
  110. package/.grok/skills/tutien/scripts/compare.mjs +41 -0
  111. package/.grok/skills/tutien/scripts/metrics.mjs +306 -0
  112. package/.grok/skills/tutien/scripts/normalize-events.mjs +68 -0
  113. package/.grok/skills/tutien/scripts/project-profile.mjs +202 -0
  114. package/.grok/skills/tutien/scripts/redact.mjs +30 -0
  115. package/.grok/skills/tutien/scripts/render-report.mjs +479 -0
  116. package/.grok/skills/tutien/scripts/response-brief.mjs +103 -0
  117. package/.grok/skills/tutien/scripts/run-tutien.mjs +350 -0
  118. package/.grok/skills/tutien/scripts/score.mjs +97 -0
  119. package/.grok/skills/tutien/scripts/snapshot.mjs +76 -0
  120. package/.grok/skills/tutien/scripts/story-ledger.mjs +241 -0
  121. package/.grok/skills/tutien/scripts/villains.mjs +196 -0
  122. package/.vibekit/docs/BACKBONE_REFERENCE.md +2 -0
  123. package/.vibekit/docs/INSTALL.md +3 -1
  124. package/.vibekit/init/CLAUDE-template.md +2 -0
  125. package/.vibekit/scripts/mvck.mjs +5 -5
  126. package/.vibekit/scripts/pack-dry-run.mjs +38 -3
  127. package/.vibekit/scripts/validate-kit.mjs +34 -24
  128. package/.vibekit/skills/claim/SKILL.md +82 -0
  129. package/.vibekit/skills/skills-manifest.json +27 -0
  130. package/.vibekit/skills/tutien/SKILL.md +97 -0
  131. package/.vibekit/skills/tutien/references/adaptive-response.md +68 -0
  132. package/.vibekit/skills/tutien/references/classification.md +64 -0
  133. package/.vibekit/skills/tutien/references/lore-sources.md +43 -0
  134. package/.vibekit/skills/tutien/references/privacy.md +45 -0
  135. package/.vibekit/skills/tutien/references/schema.md +106 -0
  136. package/.vibekit/skills/tutien/references/scoring-and-realms.md +37 -0
  137. package/.vibekit/skills/tutien/references/story-system.md +176 -0
  138. package/.vibekit/skills/tutien/references/vi-style-guide.md +89 -0
  139. package/.vibekit/skills/tutien/references/voice-and-mode.md +59 -0
  140. package/.vibekit/skills/tutien/scripts/adapters/generic-jsonl.mjs +82 -0
  141. package/.vibekit/skills/tutien/scripts/adapters/git.mjs +48 -0
  142. package/.vibekit/skills/tutien/scripts/adapters/plain-transcript.mjs +37 -0
  143. package/.vibekit/skills/tutien/scripts/analyze-history.mjs +84 -0
  144. package/.vibekit/skills/tutien/scripts/catalog.mjs +130 -0
  145. package/.vibekit/skills/tutien/scripts/classify.mjs +338 -0
  146. package/.vibekit/skills/tutien/scripts/command.mjs +126 -0
  147. package/.vibekit/skills/tutien/scripts/compare.mjs +41 -0
  148. package/.vibekit/skills/tutien/scripts/metrics.mjs +306 -0
  149. package/.vibekit/skills/tutien/scripts/normalize-events.mjs +68 -0
  150. package/.vibekit/skills/tutien/scripts/project-profile.mjs +202 -0
  151. package/.vibekit/skills/tutien/scripts/redact.mjs +30 -0
  152. package/.vibekit/skills/tutien/scripts/render-report.mjs +479 -0
  153. package/.vibekit/skills/tutien/scripts/response-brief.mjs +103 -0
  154. package/.vibekit/skills/tutien/scripts/run-tutien.mjs +350 -0
  155. package/.vibekit/skills/tutien/scripts/score.mjs +97 -0
  156. package/.vibekit/skills/tutien/scripts/snapshot.mjs +76 -0
  157. package/.vibekit/skills/tutien/scripts/story-ledger.mjs +241 -0
  158. package/.vibekit/skills/tutien/scripts/villains.mjs +196 -0
  159. package/CHANGELOG.md +51 -0
  160. package/README.md +53 -47
  161. package/docs/README.vi.md +14 -8
  162. package/docs/README.zh-CN.md +279 -0
  163. package/package.json +9 -3
@@ -0,0 +1,130 @@
1
+ // Problem-to-practice catalog. Data-driven so new problem types can be added
2
+ // without touching the analyzer. Each entry carries an existing project skill
3
+ // or convention as the concrete counter-technique, plus a villain archetype
4
+ // that the Phase 3 engine may (optionally) surface. Detection is evidence-
5
+ // bound: a problem needs real event references and a confidence, never a
6
+ // single ambiguous signal.
7
+
8
+ export const CATALOG = {
9
+ 'repeated-failure': {
10
+ problemType: 'repeated-failure',
11
+ counterTechnique: { vi: 'Dừng sau lần thất bại thứ hai giống nhau; lập giả thuyết mới trước khi thử lại.', en: 'Stop after the second identical failure; form a new hypothesis before retrying.' },
12
+ projectHelp: 'sequential-thinking',
13
+ microQuest: { vi: 'Lần lặp kế tiếp: viết một giả thuyết mới trước khi chạy lại.', en: 'Next iteration: write one new hypothesis before re-running.' },
14
+ victory: { vi: 'Một nhiệm vụ khép lại mà không có ba lần thử giống nhau.', en: 'A task closes without three identical retries.' },
15
+ ifThen: { vi: 'Nếu cùng một lệnh thất bại hai lần, thì dừng thử lại và viết một giả thuyết mới.', en: 'If the same command fails twice, then stop retrying and write a new hypothesis.' },
16
+ villain: { name: 'Luân Hồi Ma Ảnh', gloss: 'Error-Cycle Wraith' }
17
+ },
18
+ 'too-many-prompts': {
19
+ problemType: 'too-many-prompts',
20
+ counterTechnique: { vi: 'Chia nhiệm vụ thành các chặng kiểm chứng; mỗi chặng có một kết quả rõ ràng.', en: 'Split the task into checkpoints with a validation result at each boundary.' },
21
+ projectHelp: 'clearthought',
22
+ microQuest: { vi: 'Nhiệm vụ tới: xác định hai chặng kiểm chứng có tiêu chí hoàn thành.', en: 'Next task: define 2 checkpoints each with a done-criterion.' },
23
+ victory: { vi: 'Nhiệm vụ hoàn thành với số lượt yêu cầu thấp hơn ngưỡng lịch sử.', en: 'A task completes under the historical prompt threshold.' },
24
+ ifThen: { vi: 'Nếu gửi lượt yêu cầu thứ ba cho cùng một nhiệm vụ, hãy đặt một chặng kiểm chứng có tiêu chí hoàn thành trước.', en: 'If you send a third prompt on one task, then define a checkpoint with a done-criterion first.' },
25
+ villain: { name: 'Cửu Hoàn Tâm Ma', gloss: 'Ninefold Loop Heart-Shadow' }
26
+ },
27
+ 'conflicting-instructions': {
28
+ problemType: 'conflicting-instructions',
29
+ counterTechnique: { vi: 'Lập sổ ưu tiên và ràng buộc; nêu rõ chỉ thị nào thay thế chỉ thị nào.', en: 'Build a precedence and constraint ledger; state which instruction supersedes which.' },
30
+ projectHelp: 'claim',
31
+ microQuest: { vi: 'Trước khi sửa: ghi một dòng nêu rõ điều được phép và điều không được phép.', en: 'Before editing: write one allowed/forbidden line.' },
32
+ victory: { vi: 'Không còn cặp chỉ thị mâu thuẫn chưa giải quyết trong một nhiệm vụ.', en: 'No unresolved contradictory instruction pair remains in a task.' },
33
+ ifThen: { vi: 'Nếu chỉ thị mới mâu thuẫn với chỉ thị trước, thì nêu rõ chỉ thị nào thắng trước khi sửa.', en: 'If a new instruction contradicts an earlier one, then state which one wins before editing.' },
34
+ villain: { name: 'Nghịch Lệnh Ma Quân', gloss: 'Lord of Clashing Edicts' }
35
+ },
36
+ 'unrecovered-failure': {
37
+ problemType: 'unrecovered-failure',
38
+ counterTechnique: { vi: 'Thêm cổng hoàn thành: chạy kiểm chứng và đính kèm kết quả.', en: 'Add a completion gate: run validation and attach a result receipt.' },
39
+ projectHelp: 'backbone.yml validate',
40
+ microQuest: { vi: 'Với mỗi lỗi còn treo: chạy lại đúng kiểm tra đó tới khi đạt.', en: 'For each open failure: re-run that exact check until it passes.' },
41
+ victory: { vi: 'Mỗi thất bại có một lần kiểm chứng đạt tương ứng về sau.', en: 'Every failure has a later matching pass.' },
42
+ ifThen: { vi: 'Nếu một kiểm tra thất bại, hãy chạy lại đúng kiểm tra đó tới khi đạt trước khi làm việc mới.', en: 'If a check fails, then re-run that exact check until it passes before starting new work.' },
43
+ villain: { name: 'Vô Nghiệm Ảnh Quân', gloss: 'Unverified Trial Wraith' }
44
+ },
45
+ 'work-without-proof': {
46
+ problemType: 'work-without-proof',
47
+ counterTechnique: { vi: 'Chạy lệnh kiểm chứng của kho mã và gắn kết quả trước khi tuyên bố hoàn thành.', en: 'Run the repository validation and attach the result before declaring done.' },
48
+ projectHelp: 'backbone.yml validate',
49
+ microQuest: { vi: 'Bản ghi Git tiếp theo: kèm một dòng kết quả kiểm chứng.', en: 'Next commit: include one validation-result line.' },
50
+ victory: { vi: 'Mỗi vùng công việc có ít nhất một sự kiện kiểm chứng.', en: 'Every work window has at least one validation event.' },
51
+ ifThen: { vi: 'Nếu sắp tuyên bố hoàn thành, hãy chạy lệnh kiểm chứng của kho mã và đính kèm kết quả trước.', en: "If you are about to say 'done', then run the repo validation and attach the result first." },
52
+ villain: { name: 'Vô Chứng Đan Ảnh', gloss: 'Proofless Elixir Shade' }
53
+ }
54
+ };
55
+
56
+ const clamp01 = (x) => Math.max(0, Math.min(1, x));
57
+ const round3 = (x) => Math.round(x * 1000) / 1000;
58
+
59
+ // Returns ranked, actionable problems. priority = impact × recurrence ×
60
+ // confidence × fixability. Only problems with confidence >= minConfidence and
61
+ // priority >= minPriority survive; at most `top` are returned.
62
+ export function detectProblems(analysis, { minConfidence = 0.5, minPriority = 0.12, top = 3 } = {}) {
63
+ const found = [];
64
+ const rep = analysis.repetition ?? {};
65
+ const issues = analysis.issues ?? {};
66
+ const failures = issues.failures ?? [];
67
+ const recoveries = issues.recoveries ?? [];
68
+
69
+ for (const loop of rep.retryLoopCandidates ?? []) {
70
+ // Only failures attributed to this loop's own task make it a failure loop;
71
+ // an unrelated failure elsewhere must not change the classification.
72
+ const isFailing = failures.some((f) => f.taskId != null && f.taskId === loop.taskId);
73
+ const id = isFailing ? 'repeated-failure' : 'too-many-prompts';
74
+ found.push({
75
+ problemId: id,
76
+ evidence: { taskId: loop.taskId, repeatCount: loop.count, eventIds: loop.eventIds },
77
+ confidence: loop.confidence,
78
+ impact: isFailing ? 0.7 : 0.5,
79
+ recurrence: clamp01(loop.count / 4),
80
+ fixability: 0.8
81
+ });
82
+ }
83
+
84
+ const conflicts = analysis.conflicts ?? [];
85
+ if (conflicts.length > 0) {
86
+ found.push({
87
+ problemId: 'conflicting-instructions',
88
+ evidence: { count: conflicts.length, eventIds: conflicts.flatMap((c) => c.eventIds) },
89
+ confidence: Math.max(...conflicts.map((c) => c.confidence)),
90
+ impact: 0.7,
91
+ recurrence: clamp01(conflicts.length / 2),
92
+ fixability: 0.7
93
+ });
94
+ }
95
+
96
+ const unrecovered = failures.filter((f) => !recoveries.some((r) => r.issueEventId === f.eventId));
97
+ if (unrecovered.length > 0) {
98
+ found.push({
99
+ problemId: 'unrecovered-failure',
100
+ evidence: { count: unrecovered.length, eventIds: unrecovered.map((f) => f.eventId) },
101
+ confidence: 0.7,
102
+ impact: 0.8,
103
+ recurrence: clamp01(unrecovered.length / 3),
104
+ fixability: 0.6
105
+ });
106
+ }
107
+
108
+ const commits = analysis.coverage?.commits ?? 0;
109
+ const validationEvents = (issues.passes ?? 0) + failures.length;
110
+ if (commits > 0 && validationEvents === 0) {
111
+ found.push({
112
+ problemId: 'work-without-proof',
113
+ evidence: { commits, validationEvents: 0 },
114
+ confidence: 0.6,
115
+ impact: 0.6,
116
+ recurrence: clamp01(commits / 5),
117
+ fixability: 0.7
118
+ });
119
+ }
120
+
121
+ return found
122
+ .map((p) => {
123
+ const meta = CATALOG[p.problemId];
124
+ const priority = round3(p.impact * p.recurrence * p.confidence * p.fixability);
125
+ return { ...p, priority, confidence: round3(p.confidence), meta };
126
+ })
127
+ .filter((p) => p.confidence >= minConfidence && p.priority >= minPriority)
128
+ .sort((a, b) => b.priority - a.priority || a.problemId.localeCompare(b.problemId))
129
+ .slice(0, top);
130
+ }
@@ -0,0 +1,338 @@
1
+ // Tu Tiên project-classification and progression system. Three orthogonal
2
+ // axes plus a knowledge taxonomy and seven progression metrics:
3
+ // - Dao faction = the PROJECT's ethical/risk posture;
4
+ // - affiliation = the cultivator's ORGANIZATIONAL mode (never ethics:
5
+ // Tán Tu is independence, not the opposite of Tà Tu);
6
+ // - paths = the project's TECHNICAL nature (multi-select).
7
+ //
8
+ // One fail-closed POLICY STATE governs the whole report. Only `clear` may
9
+ // enable lore, villains, recommendations, score, realm, and positive
10
+ // progression:
11
+ // - declared-stop : user declared Tà Đạo / Tà Tu — a stop signal;
12
+ // - needs-review : intent-to-harm signals — no Dao assignment,
13
+ // no gamification, ask for human review;
14
+ // - authorization-required : Ma Đạo without a valid authorization slug;
15
+ // - clear : lawful constructive work.
16
+ // The engine NEVER auto-assigns Tà Đạo / Tà Tu (intent to harm cannot be
17
+ // judged lexically; difficulty is not evil), and never labels harmful text
18
+ // "righteous" — harm produces an undetermined faction and needs-review.
19
+
20
+ import crypto from 'node:crypto';
21
+
22
+ const clamp01 = (x) => Math.max(0, Math.min(1, x));
23
+ const round3 = (x) => Math.round(x * 1000) / 1000;
24
+ const sha16 = (s) => crypto.createHash('sha256').update(s).digest('hex').slice(0, 16);
25
+
26
+ export const FACTIONS = {
27
+ 'chinh-dao': { name: 'Chính Đạo', gloss: { vi: 'chính phái, hợp pháp, minh bạch và tạo giá trị cho người dùng', en: 'Righteous Dao — lawful, transparent, constructive, user-beneficial' }, rank: 'normal' },
28
+ 'bang-mon': { name: 'Bàng Môn (Kỳ Đạo)', gloss: { vi: 'phi truyền thống, thử nghiệm, sáng tạo, chuyên biệt và không gây hại', en: 'Heterodox Dao — unconventional, experimental, creative, specialized; not harmful' }, rank: 'normal' },
29
+ 'ma-dao': { name: 'Ma Đạo', gloss: { vi: 'kỹ thuật rủi ro cao hoặc đối kháng; cần ủy quyền và giám sát rõ ràng', en: 'Demonic Dao — high-risk, adversarial, restricted technical work requiring explicit authorization and oversight' }, rank: 'restricted' },
30
+ 'ta-dao': { name: 'Tà Đạo', gloss: { vi: 'cố ý gây hại, bóc lột hoặc phi pháp; không bao giờ là con đường tu luyện', en: 'Evil Dao — intentionally harmful, exploitative, unlawful — never a progression path' }, rank: 'forbidden' }
31
+ };
32
+ // Not a real faction — the result of refusing to classify harmful intent.
33
+ const UNDETERMINED_FACTION = { id: 'undetermined', name: 'Chưa phân định', gloss: { vi: 'chưa gán đạo; cần con người rà soát', en: 'undetermined — needs human review' }, rank: 'review' };
34
+
35
+ export const AFFILIATIONS = {
36
+ 'tong-mon': { name: 'Tông Môn Đệ Tử', gloss: { vi: 'làm việc trong đội nhóm, tổ chức hoặc quy trình có sẵn', en: 'works within a team, organization, or established process' } },
37
+ 'tan-tu': { name: 'Tán Tu', gloss: { vi: 'tu luyện độc lập, không thuộc tổ chức cố định', en: 'works independently, outside a fixed organization or tradition' } },
38
+ 'khach-khanh': { name: 'Khách Khanh', gloss: { vi: 'chuyên gia bên ngoài hoặc cộng tác tạm thời', en: 'external expert or temporary contributor' } },
39
+ 'an-tu': { name: 'Ẩn Tu', gloss: { vi: 'nghiên cứu riêng tư, dài hạn, chuyên sâu', en: 'private, long-term, deeply focused research' } }
40
+ };
41
+
42
+ export const PATHS = {
43
+ kiem: { name: 'Kiếm Tu', gloss: { vi: 'triển khai phần mềm trực tiếp, giải quyết vấn đề nhanh', en: 'direct implementation and fast problem-solving' } },
44
+ tran: { name: 'Trận Tu', gloss: { vi: 'kiến trúc, DevOps, hạ tầng, mạng, điều phối hệ thống', en: 'architecture, DevOps, infrastructure, networking, orchestration' } },
45
+ phu: { name: 'Phù Tu', gloss: { vi: 'lời yêu cầu, tập lệnh, tự động hóa và quy trình lặp lại được', en: 'prompts, scripts, automation, repeatable workflows' } },
46
+ khi: { name: 'Khí Tu', gloss: { vi: 'công cụ, thư viện, thành phần tái sử dụng, nền tảng', en: 'tools, libraries, reusable components, platform engineering' } },
47
+ dan: { name: 'Đan Tu', gloss: { vi: 'xử lý dữ liệu, tối ưu, biến đổi, tổng hợp tài nguyên', en: 'data processing, optimization, transformation, resource synthesis' } },
48
+ y: { name: 'Y Tu', gloss: { vi: 'gỡ lỗi, bảo trì, khắc phục sự cố và hỗ trợ kỹ thuật', en: 'debugging, maintenance, incident recovery, support' } },
49
+ huyen: { name: 'Huyễn Tu', gloss: { vi: 'UI/UX, chuyển động, thiết kế, 3D và giao diện sáng tạo', en: 'UI/UX, animation, visual design, 3D, creative interfaces' } },
50
+ 'ngu-thu': { name: 'Ngự Thú Tu', gloss: { vi: 'điều phối tác nhân AI, bot và nhiều mô hình', en: 'AI-agent, bot, or multi-model orchestration' } },
51
+ 'huyen-co': { name: 'Huyền Cơ Tu', gloss: { vi: 'mật mã, thuật toán khó, bài toán phân tích hóc búa', en: 'cryptography, advanced algorithms, hard analytical problems' } },
52
+ anh: { name: 'Ảnh Tu', gloss: { vi: 'an ninh mạng có ủy quyền, điều tra số, OSINT và dịch ngược', en: 'authorized cybersecurity, forensics, investigation, OSINT, reverse engineering' } },
53
+ ta: { name: 'Tà Tu', gloss: { vi: 'phương pháp cố ý gây hại; không bao giờ gán chỉ vì dự án khó hay thuộc mảng bảo mật', en: 'intentionally harmful methods — never assigned merely because work is difficult or security-related' } }
54
+ };
55
+
56
+ export const KNOWLEDGE_KINDS = {
57
+ 'tam-phap': { name: 'Tâm pháp', gloss: { vi: 'nguyên tắc tư duy cốt lõi', en: 'core reasoning principles and mindset' } },
58
+ 'cong-phap': { name: 'Công pháp', gloss: { vi: 'chiến lược làm việc lặp lại được, dài hạn', en: 'repeatable strategies and long-term working methods' } },
59
+ 'thuat-phap': { name: 'Thuật pháp', gloss: { vi: 'kỹ thuật hoặc mẫu lời yêu cầu đơn lẻ', en: 'individual prompt patterns or techniques' } },
60
+ 'bi-thuat': { name: 'Bí thuật', gloss: { vi: 'kỹ thuật hiếm, chuyên sâu', en: 'rare, specialized, advanced techniques' } },
61
+ 'than-thong': { name: 'Thần thông', gloss: { vi: 'năng lực đã thuần thục, tái sử dụng tin cậy', en: 'highly mastered, reliably reusable abilities' } },
62
+ 'phap-bao': { name: 'Pháp bảo', gloss: { vi: 'công cụ, tập lệnh, khuôn mẫu và tác nhân hỗ trợ của bộ kỹ năng', en: 'tools, scripts, templates, agents (kit skills & commands)' } },
63
+ 'dao-dien': { name: 'Bí tịch và đạo điển', gloss: { vi: 'sổ tay, tệp kỹ năng và tài liệu tích lũy', en: 'written playbooks, skill files, accumulated documentation' } }
64
+ };
65
+
66
+ export function localizeRationale(value, language = 'en') {
67
+ const text = String(value ?? '');
68
+ if (language !== 'vi') return text;
69
+ if (text === 'declared by the user') return 'do người dùng khai báo';
70
+ if (text === 'default for lawful constructive work; no adversarial or experimental signals') {
71
+ return 'mặc định cho công việc hợp pháp và tạo giá trị; không có dấu hiệu đối kháng hoặc thử nghiệm';
72
+ }
73
+ if (text === 'single commit-author identifier (low-confidence hint)') return 'một mã tác giả Git; dấu hiệu có độ tin cậy thấp';
74
+ if (text === 'no author evidence; defaulting — declare affiliation= to correct') {
75
+ return 'không có bằng chứng về tác giả; tạm dùng giá trị mặc định. Có thể dùng `affiliation=` để sửa';
76
+ }
77
+ const authors = text.match(/^(\d+) distinct commit-author identifiers/);
78
+ if (authors) return `${authors[1]} mã tác giả Git riêng biệt; dấu hiệu có độ tin cậy thấp. Dùng \`affiliation=\` để xác nhận`;
79
+ const tagged = [
80
+ ['profile keywords: ', 'từ khóa hồ sơ: '],
81
+ ['intent-to-harm signals: ', 'dấu hiệu chủ đích gây hại: '],
82
+ ['adversarial engagement signals: ', 'dấu hiệu công việc đối kháng: '],
83
+ ['experimental/creative signals: ', 'dấu hiệu thử nghiệm hoặc sáng tạo: ']
84
+ ].find(([prefix]) => text.startsWith(prefix));
85
+ if (tagged) {
86
+ const values = text.slice(tagged[0].length).split(', ').filter(Boolean).map((item) => `\`${item}\``).join(', ');
87
+ return `${tagged[1]}${values}`;
88
+ }
89
+ return text;
90
+ }
91
+
92
+ // Word/phrase-boundary matcher: boundaries are non-alphanumeric, so "ui" does
93
+ // not match inside "build" and "api" does not match inside "rapid".
94
+ function hasKeyword(text, kw) {
95
+ const esc = kw.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
96
+ return new RegExp(`(^|[^a-z0-9])${esc}([^a-z0-9]|$)`, 'i').test(text);
97
+ }
98
+
99
+ const PATH_KEYWORDS = {
100
+ kiem: ['implementation', 'feature', 'application', 'app', 'api', 'backend', 'frontend', 'cli', 'bugfix', 'coding'],
101
+ tran: ['architecture', 'devops', 'infrastructure', 'kubernetes', 'docker', 'network', 'deploy', 'orchestration', 'ci/cd', 'terraform'],
102
+ phu: ['prompt', 'prompts', 'script', 'scripts', 'automation', 'workflow', 'skill file', 'slash command'],
103
+ khi: ['library', 'sdk', 'framework', 'platform', 'component', 'toolkit', 'kit', 'reusable'],
104
+ dan: ['data', 'etl', 'pipeline', 'optimization', 'transformation', 'database', 'analytics'],
105
+ y: ['debug', 'maintenance', 'incident', 'support', 'recovery', 'hotfix', 'triage'],
106
+ huyen: ['ui', 'ux', 'design', 'animation', '3d', 'visual', 'interface', 'creative'],
107
+ 'ngu-thu': ['agent', 'bot', 'llm', 'multi-model', 'mcp', 'ai orchestration', 'assistant'],
108
+ 'huyen-co': ['cryptography', 'cipher', 'algorithm', 'decryption', 'mathematical', 'proof'],
109
+ anh: ['security', 'pentest', 'forensics', 'osint', 'reverse engineering', 'vulnerability', 'ctf', 'audit', 'incident response', 'threat']
110
+ };
111
+
112
+ const BANG_MON_KEYWORDS = ['experimental', 'prototype', 'research', 'creative', 'art project', 'demo', 'playground', 'unconventional', 'exploratory'];
113
+ const ADVERSARIAL_KEYWORDS = ['pentest', 'red team', 'offensive security', 'exploit development', 'attack simulation', 'adversarial engagement', 'malware analysis'];
114
+ // Intent-to-harm-others signals. These route to needs-review (undetermined
115
+ // faction), NOT to an automatic Tà label. Curated to avoid dual-use overlap
116
+ // with authorized security work.
117
+ const HARM_KEYWORDS = [
118
+ 'steal', 'exfiltrate', 'malware', 'ransomware', 'phishing', 'spyware', 'keylogger', 'botnet',
119
+ 'defraud', 'fraud', 'scam', 'sabotage', 'backdoor', 'ddos', 'without consent', 'without authorization',
120
+ 'without permission', 'illegal', 'illegally', 'unlawful', 'harm competitor', 'harm competitors',
121
+ 'harm user', 'harm users', 'harm others', 'attack a bank', 'attack users', 'attack a company'
122
+ ];
123
+
124
+ // Authorization is a user-ASSERTED reference only, never verified. Accept a
125
+ // bounded safe slug; reject secret-shaped values, markup, URLs, and anything
126
+ // with '=' (which a `key=value` secret would carry).
127
+ const AUTH_SLUG = /^[a-z0-9][a-z0-9_-]{0,63}$/i;
128
+ export function validateAuthorization(value) {
129
+ if (value == null) return { recorded: false, reference: null, rejected: false };
130
+ if (typeof value === 'string' && AUTH_SLUG.test(value)) return { recorded: true, reference: value, rejected: false };
131
+ return { recorded: false, reference: null, rejected: true };
132
+ }
133
+
134
+ const textOf = (profile) =>
135
+ [profile.description ?? '', ...(profile.domains ?? []), profile.projectType ?? '', profile.primaryLanguage ?? '']
136
+ .join(' ')
137
+ .toLowerCase();
138
+
139
+ export function validateDeclarations(declared = {}) {
140
+ const errors = [];
141
+ if (declared.faction && !FACTIONS[declared.faction]) errors.push(`unknown faction "${declared.faction}"; valid: ${Object.keys(FACTIONS).join(', ')}`);
142
+ if (declared.affiliation && !AFFILIATIONS[declared.affiliation]) errors.push(`unknown affiliation "${declared.affiliation}"; valid: ${Object.keys(AFFILIATIONS).join(', ')}`);
143
+ const paths = declared.paths ?? [];
144
+ for (const p of paths) {
145
+ if (!PATHS[p]) errors.push(`unknown path "${p}"; valid: ${Object.keys(PATHS).join(', ')}`);
146
+ }
147
+ // Tà Tu is an exclusive stop declaration; it must not be combined with real
148
+ // cultivation paths (fail closed rather than mixing lore with a stop state).
149
+ if (paths.includes('ta') && paths.length > 1) errors.push('path "ta" (Tà Tu) is an exclusive stop declaration and cannot be combined with other paths');
150
+ return errors;
151
+ }
152
+
153
+ export function classifyProject(profile = {}) {
154
+ const errors = validateDeclarations(profile.declared ?? {});
155
+ if (errors.length) throw new Error(errors.join('; '));
156
+ const declared = profile.declared ?? {};
157
+ const text = textOf(profile);
158
+ const harmSignals = HARM_KEYWORDS.filter((k) => hasKeyword(text, k));
159
+ const declaredStop = declared.faction === 'ta-dao' || (declared.paths ?? []).includes('ta');
160
+
161
+ // --- paths (multi-select), declared first (order preserved) ---
162
+ const paths = [];
163
+ for (const id of declared.paths ?? []) paths.push({ id, ...PATHS[id], confidence: 0.95, rationale: 'declared by the user', declared: true });
164
+ for (const [id, keywords] of Object.entries(PATH_KEYWORDS)) {
165
+ if (paths.some((p) => p.id === id)) continue;
166
+ const hits = keywords.filter((k) => hasKeyword(text, k));
167
+ if (hits.length) paths.push({ id, ...PATHS[id], confidence: clamp01(0.5 + hits.length * 0.15), rationale: `profile keywords: ${hits.join(', ')}`, declared: false, hitCount: hits.length });
168
+ }
169
+ const declaredPaths = paths.filter((p) => p.declared);
170
+ const detectedPaths = paths.filter((p) => !p.declared).sort((a, b) => b.confidence - a.confidence || b.hitCount - a.hitCount || a.id.localeCompare(b.id));
171
+ const orderedPaths = [...declaredPaths, ...detectedPaths];
172
+
173
+ // --- faction (precedence: declared-stop → harm → declared → detected) ---
174
+ let faction;
175
+ if (declaredStop) {
176
+ faction = { id: 'ta-dao', ...FACTIONS['ta-dao'], confidence: 0.95, rationale: 'declared by the user' };
177
+ } else if (harmSignals.length) {
178
+ faction = { id: 'undetermined', ...UNDETERMINED_FACTION, confidence: 0.9, rationale: `intent-to-harm signals: ${harmSignals.join(', ')}` };
179
+ } else if (declared.faction) {
180
+ faction = { id: declared.faction, ...FACTIONS[declared.faction], confidence: 0.95, rationale: 'declared by the user' };
181
+ } else {
182
+ const adversarial = ADVERSARIAL_KEYWORDS.filter((k) => hasKeyword(text, k));
183
+ const bangMon = BANG_MON_KEYWORDS.filter((k) => hasKeyword(text, k));
184
+ if (adversarial.length) faction = { id: 'ma-dao', ...FACTIONS['ma-dao'], confidence: clamp01(0.6 + adversarial.length * 0.1), rationale: `adversarial engagement signals: ${adversarial.join(', ')}` };
185
+ else if (bangMon.length) faction = { id: 'bang-mon', ...FACTIONS['bang-mon'], confidence: clamp01(0.55 + bangMon.length * 0.1), rationale: `experimental/creative signals: ${bangMon.join(', ')}` };
186
+ else faction = { id: 'chinh-dao', ...FACTIONS['chinh-dao'], confidence: 0.6, rationale: 'default for lawful constructive work; no adversarial or experimental signals' };
187
+ }
188
+
189
+ if (faction.id === 'ma-dao') faction.authorization = validateAuthorization(profile.authorization);
190
+
191
+ // --- output policy: single fail-closed projection ---
192
+ let policyState;
193
+ if (declaredStop) policyState = 'declared-stop';
194
+ else if (faction.id === 'undetermined') policyState = 'needs-review';
195
+ else if (faction.id === 'ma-dao' && !faction.authorization.recorded) policyState = 'authorization-required';
196
+ else policyState = 'clear';
197
+ const policy = { state: policyState, canGamify: policyState === 'clear', canRecommend: policyState === 'clear' };
198
+
199
+ // --- affiliation (organizational only — independent of ethics) ---
200
+ let affiliation;
201
+ if (declared.affiliation) affiliation = { id: declared.affiliation, ...AFFILIATIONS[declared.affiliation], confidence: 0.95, rationale: 'declared by the user' };
202
+ else if (Number.isFinite(profile.authorsCount) && profile.authorsCount > 1) affiliation = { id: 'tong-mon', ...AFFILIATIONS['tong-mon'], confidence: 0.55, rationale: `${profile.authorsCount} distinct commit-author identifiers (low-confidence hint; declare affiliation= to confirm)` };
203
+ else if (profile.authorsCount === 1) affiliation = { id: 'tan-tu', ...AFFILIATIONS['tan-tu'], confidence: 0.5, rationale: 'single commit-author identifier (low-confidence hint)' };
204
+ else affiliation = { id: 'tan-tu', ...AFFILIATIONS['tan-tu'], confidence: 0.4, rationale: 'no author evidence; defaulting — declare affiliation= to correct' };
205
+
206
+ // --- knowledge: primary = first declared path, else strongest detected ---
207
+ const primaryPath = declaredPaths[0]?.id ?? detectedPaths[0]?.id ?? 'kiem';
208
+ const knowledge = policy.canRecommend ? knowledgeFor(primaryPath) : null;
209
+
210
+ const dualUse = orderedPaths.some((p) => p.id === 'anh' || p.id === 'huyen-co');
211
+ const explanation = buildExplanation(faction, policy, dualUse);
212
+
213
+ return { faction, policy, affiliation, paths: orderedPaths, primaryPath, knowledge, explanation, dualUse, harmSignals, suppressGamification: !policy.canGamify };
214
+ }
215
+
216
+ const PATH_KNOWLEDGE = {
217
+ kiem: { tamPhap: { vi: 'Thay đổi nhỏ nhất mà đúng; kiểm chứng sau mỗi lần sửa.', en: 'Smallest correct change; validate after every edit.' }, congPhap: { vi: 'Vòng lặp theo chặng: sửa nhỏ, kiểm chứng, xác nhận rồi mới đi tiếp.', en: 'Checkpoint loop: small edit → validation → confirm before moving on.' }, biThuat: { vi: 'Tách lần tái cấu trúc lớn thành chuỗi `diff` nhỏ có thể đảo ngược.', en: 'Decompose a large refactor into a chain of small reversible diffs.' }, thanThong: { vi: 'Đọc hiểu kho mã lạ và định vị đúng điểm sửa ngay lần đầu.', en: 'Read an unfamiliar codebase and locate the right edit on the first pass.' }, phapBao: ['prompt-sharpener', 'sequential-thinking'] },
218
+ tran: { tamPhap: { vi: 'Vẽ ranh giới và hợp đồng giữa các thành phần trước khi nối chúng.', en: 'Draw component boundaries and contracts before wiring them.' }, congPhap: { vi: 'Mọi thay đổi hạ tầng đều có đường lùi được diễn tập.', en: 'Every infrastructure change ships with a rehearsed rollback.' }, biThuat: { vi: 'Mô phỏng sự cố có kiểm soát trước khi sự cố thật xảy ra.', en: 'Controlled failure rehearsal before the real incident.' }, thanThong: { vi: 'Thiết kế hệ thống chịu lỗi mà không giấu đi độ bất định.', en: 'Design fault-tolerant systems without hiding uncertainty.' }, phapBao: ['clearthought', 'path-sensitive-shell-safety'] },
219
+ phu: { tamPhap: { vi: 'Một quy trình lặp lại được đáng giá hơn mười lần làm tay.', en: 'One repeatable workflow beats ten manual runs.' }, congPhap: { vi: 'Chuẩn hóa lời yêu cầu thành `skill` có tiêu chí hoàn thành rõ ràng.', en: 'Formalize prompts into skills with explicit done-criteria.' }, biThuat: { vi: 'Cơ chế tự kiểm: quy trình tự phát hiện khi chính nó sai.', en: 'Self-checking guardrails: the workflow detects its own failure.' }, thanThong: { vi: 'Biến một việc thủ công lặp lại thành lệnh chạy một lần đáng tin cậy.', en: 'Turn a repeated manual chore into a reliable one-shot command.' }, phapBao: ['prompt-sharpener', 'claim'] },
220
+ khi: { tamPhap: { vi: 'API là lời hứa; đặt tên và hành vi phải giữ được lời.', en: 'An API is a promise; naming and behavior must keep it.' }, congPhap: { vi: 'Dùng sổ đăng ký trung tâm và kiểm tra tính đồng nhất để bản phân phối không trôi.', en: 'Central registry + parity checks so distribution never drifts.' }, biThuat: { vi: 'Mẫu kiểm thử âm: cố tình làm hỏng để chứng minh bộ kiểm tra phát hiện được.', en: 'Negative fixtures: break it on purpose to prove the validator catches it.' }, thanThong: { vi: 'Thiết kế thành phần tái sử dụng mà người khác dùng đúng ngay.', en: 'Design reusable components others use correctly on the first try.' }, phapBao: ['claim', 'daily-workflow-curator'] },
221
+ dan: { tamPhap: { vi: 'Số liệu tách bạch theo nguồn gốc: đo được, ước lượng, không rõ.', en: 'Numbers stay split by provenance: measured, estimated, unknown.' }, congPhap: { vi: 'Đặt mốc chuẩn trước, biến đổi sau và ghi nhật ký so sánh.', en: 'Baseline first, transform second, logged comparison always.' }, biThuat: { vi: 'Thiết kế chuỗi xử lý có thể chạy lại từ bất kỳ điểm gãy nào.', en: 'Pipelines resumable from any break point.' }, thanThong: { vi: 'Chuyển dữ liệu thô hỗn độn thành dạng đáng tin, đo được.', en: 'Turn messy raw data into a trustworthy, measurable shape.' }, phapBao: ['autoresearch-coding', 'sequential-thinking'] },
222
+ y: { tamPhap: { vi: 'Chẩn bệnh trước, kê đơn sau: tái hiện lỗi trước khi sửa.', en: 'Diagnose before prescribing: reproduce before fixing.' }, congPhap: { vi: 'Nếu hai lần thất bại giống nhau, hãy dừng và lập giả thuyết mới.', en: 'Two identical failures → stop, form a new hypothesis.' }, biThuat: { vi: 'Thu nhỏ ca lỗi tới ví dụ tối giản còn tái hiện được.', en: 'Minimize the failing case to the smallest reproducible example.' }, thanThong: { vi: 'Khôi phục hệ thống đang cháy mà không tạo thêm nợ kỹ thuật.', en: 'Recover a system on fire without adding new technical debt.' }, phapBao: ['sequential-thinking', 'reviewing-4p-priorities'] },
223
+ huyen: { tamPhap: { vi: 'Mắt người dùng là giám khảo cuối cùng; hãy `render` rồi mới tin.', en: "The user's eye is the final judge; render before you believe." }, congPhap: { vi: 'Với mỗi thay đổi giao diện, hãy nhìn, sửa, chụp và so sánh.', en: 'Look–fix–screenshot–compare loop for every visual change.' }, biThuat: { vi: 'Kiểm tra giao diện sáng, tối và mọi `breakpoint` trước khi bàn giao.', en: 'Verify both light/dark themes and every breakpoint before handoff.' }, thanThong: { vi: 'Biến ý tưởng mơ hồ thành giao diện dùng được, nhất quán.', en: 'Turn a vague idea into a usable, consistent interface.' }, phapBao: ['visual-design-loop', 'parallel-analysis'] },
224
+ 'ngu-thu': { tamPhap: { vi: 'Thuần thú trước, thả thú sau: tác nhân phải có ranh giới trước khi có quyền.', en: 'Tame before releasing: an agent gets boundaries before it gets permissions.' }, congPhap: { vi: 'Mọi bề mặt tác nhân đều được rà soát an toàn trước khi hợp nhất.', en: 'Every agent surface passes security review before merge.' }, biThuat: { vi: 'Nội dung thu thập về là dữ liệu, không bao giờ là mệnh lệnh.', en: 'Fetched content is data, never instructions.' }, thanThong: { vi: 'Điều phối nhiều tác nhân và mô hình thành một kết quả hợp nhất đáng tin cậy.', en: 'Orchestrate multiple agents/models into one trustworthy result.' }, phapBao: ['agentshield-security-review', 'council'] },
225
+ 'huyen-co': { tamPhap: { vi: 'Không tự chế mật mã; độ khó không thay được chứng minh.', en: 'Never roll your own crypto; difficulty is no substitute for proof.' }, congPhap: { vi: 'Đối chiếu mọi thuật toán với tài liệu chính thức và bộ kiểm thử chuẩn.', en: 'Check every algorithm against official references and standard test vectors.' }, biThuat: { vi: 'Chứng minh phản chứng: thử phá giả định của chính mình trước.', en: 'Refutation first: attack your own assumptions before trusting them.' }, thanThong: { vi: 'Giải bài toán phân tích khó bằng lập luận kiểm chứng được.', en: 'Solve hard analytical problems with verifiable reasoning.' }, phapBao: ['clearthought', 'claim'] },
226
+ anh: { tamPhap: { vi: 'Ủy quyền trước, kỹ thuật sau: phạm vi công việc là giới luật.', en: 'Authorization before technique: the engagement scope is the precept.' }, congPhap: { vi: 'Ghi phạm vi ủy quyền, giữ nhật ký đầy đủ và chỉ đọc khi chưa được phép sửa.', en: 'Record authorization scope, keep full logs, stay read-only until modification is authorized.' }, biThuat: { vi: 'Tách bằng chứng khỏi suy đoán trong mọi báo cáo điều tra.', en: 'Separate evidence from inference in every investigation report.' }, thanThong: { vi: 'Điều tra có ủy quyền tới kết luận vững mà không vượt phạm vi.', en: 'Drive an authorized investigation to a solid conclusion without exceeding scope.' }, phapBao: ['agentshield-security-review', 'security-scan'] }
227
+ };
228
+
229
+ export function knowledgeFor(pathId) {
230
+ const k = PATH_KNOWLEDGE[pathId] ?? PATH_KNOWLEDGE.kiem;
231
+ return {
232
+ tamPhap: k.tamPhap,
233
+ congPhap: k.congPhap,
234
+ biThuat: k.biThuat,
235
+ thanThong: k.thanThong,
236
+ phapBao: k.phapBao,
237
+ thuatPhap: { vi: 'Các thuật pháp cụ thể nằm ở mục "Tâm ma và vòng lặp". Mỗi vấn đề kèm một cách hóa giải.', en: 'Concrete Thuật Pháp live in the "Heart demons & loops" section: each problem carries its counter-technique.' },
238
+ daoDien: { vi: 'Đạo điển của kho mã gồm các tệp `SKILL.md` trong `.vibekit/skills/` và `backbone.yml`.', en: "This repo's Đạo Điển: the SKILL.md files under .vibekit/skills/ and backbone.yml." }
239
+ };
240
+ }
241
+
242
+ function buildExplanation(faction, policy, dualUse) {
243
+ const lines = { vi: [], en: [] };
244
+ if (faction.id === 'undetermined') {
245
+ lines.vi.push(`Chưa gán đạo: phát hiện ${localizeRationale(faction.rationale, 'vi')}. Báo cáo dừng phần trò chơi và yêu cầu con người rà soát. Đây không phải là gán nhãn Tà Đạo tự động; hệ thống chỉ từ chối phân loại cho tới khi được rà soát.`);
246
+ lines.en.push(`Faction undetermined: intent-to-harm signals detected (${faction.rationale}). The report withholds gamification and requests human review. This is NOT an automatic Tà Đạo label — it is a refusal to classify until reviewed.`);
247
+ return lines;
248
+ }
249
+ const viGloss = faction.gloss.vi ? `${faction.gloss.vi[0].toUpperCase()}${faction.gloss.vi.slice(1)}` : '';
250
+ lines.vi.push(`Đạo: ${faction.name}. ${viGloss} (độ tin cậy ${faction.confidence}). Căn cứ: ${localizeRationale(faction.rationale, 'vi')}.`);
251
+ lines.en.push(`Faction: ${faction.name} — ${faction.gloss.en} (confidence ${faction.confidence}). Basis: ${faction.rationale}.`);
252
+ if (dualUse) {
253
+ lines.vi.push('Lưu ý lưỡng dụng: bảo mật, điều tra, mật mã hoặc dịch ngược có ủy quyền là Ảnh Tu hay Huyền Cơ Tu và vẫn hợp đạo. Tà Tu chỉ dành cho chủ đích gây hại; độ khó kỹ thuật không phải là tà.');
254
+ lines.en.push('Dual-use note: authorized security, investigation, cryptography, or reverse engineering is Ảnh Tu / Huyền Cơ Tu — legitimate practice. Tà Tu is reserved for intent to harm; technical difficulty is not evil.');
255
+ }
256
+ if (faction.id === 'ma-dao') {
257
+ const a = faction.authorization;
258
+ if (a.recorded) { lines.vi.push(`Ủy quyền do người dùng khẳng định (chưa xác minh): "${a.reference}".`); lines.en.push(`User-asserted authorization reference (not verified): "${a.reference}".`); }
259
+ else if (a.rejected) { lines.vi.push('Tham chiếu ủy quyền bị từ chối vì chứa ký tự không an toàn hoặc có dạng bí mật. Cần một slug an toàn: `authorization=<chữ-số-gạch>`.'); lines.en.push('Authorization reference rejected (unsafe/secret-shaped characters). Provide a safe slug: authorization=<alnum-dash>.'); }
260
+ else { lines.vi.push('Ủy quyền chưa được ghi nhận. Công việc Ma Đạo tạm dừng phần trò chơi cho tới khi phạm vi công việc được ghi bằng `authorization=<slug>`.'); lines.en.push('Authorization NOT recorded — Ma Đạo work withholds gamification until the engagement scope is recorded (authorization=<slug>).'); }
261
+ }
262
+ if (policy.state === 'declared-stop') {
263
+ lines.vi.push('Tà Đạo không phải là con đường tu luyện: không cảnh giới, không Tu Vi và không Công Đức. Dừng lại để con người rà soát hoặc xác nhận ủy quyền hợp pháp.');
264
+ lines.en.push('Tà Đạo is not a cultivation path: no realm, no Tu Vi, no Công Đức. Stop and seek human review / lawful authorization.');
265
+ }
266
+ return lines;
267
+ }
268
+
269
+ export const PROGRESSION = {
270
+ tuVi: { name: 'Tu Vi', gloss: { vi: 'kinh nghiệm tích lũy', en: 'total accumulated experience' } },
271
+ daoHanh: { name: 'Đạo Hạnh', gloss: { vi: 'trải nghiệm thực chiến dài hạn', en: 'long-term practical experience' } },
272
+ ngoTinh: { name: 'Ngộ Tính', gloss: { vi: 'khả năng hiểu, thích nghi, cải thiện giải pháp', en: 'ability to understand, adapt, improve solutions' } },
273
+ doThuanThuc: { name: 'Độ Thuần Thục', gloss: { vi: 'mức thuần thục kỹ thuật', en: 'mastery of a specific technique or method' } },
274
+ tamCanh: { name: 'Tâm Cảnh', gloss: { vi: 'giữ vững hiệu quả trước bất định và bài toán khó', en: 'effectiveness under uncertainty and hard problems' } },
275
+ congDuc: { name: 'Công Đức', gloss: { vi: 'giá trị tích cực từ công việc hoàn thành', en: 'positive value generated by completed work' } },
276
+ nghiepLuc: { name: 'Nghiệp Lực', gloss: { vi: 'rủi ro, nợ kỹ thuật, hệ quả chưa giải quyết', en: 'risk, technical debt, unresolved consequences' } }
277
+ };
278
+
279
+ // Per-event progression contributions, each tied to a unique composite key so
280
+ // accumulation is idempotent: replaying the same evidence adds nothing, and a
281
+ // window with one new event adds only that event's contribution.
282
+ export function progressionContributions(analysis) {
283
+ const issues = analysis.issues ?? {};
284
+ const out = [];
285
+ for (const id of issues.passEventIds ?? []) out.push({ key: `pass:${id}`, tuVi: 1, congDuc: 1, nghiepLuc: 0 });
286
+ for (const r of issues.recoveries ?? []) out.push({ key: `recovery:${r.issueEventId}`, tuVi: 1, congDuc: 1, nghiepLuc: 0 });
287
+ (analysis.commitEventIds ?? []).slice(0, 10).forEach((id) => out.push({ key: `commit:${id}`, tuVi: 1, congDuc: 0, nghiepLuc: 0 }));
288
+ const recovered = new Set((issues.recoveries ?? []).map((r) => r.issueEventId));
289
+ for (const f of issues.failures ?? []) {
290
+ if (!recovered.has(f.eventId)) out.push({ key: `unrec:${f.eventId}`, tuVi: 0, congDuc: 0, nghiepLuc: 2 });
291
+ }
292
+ for (const c of analysis.conflicts ?? []) out.push({ key: `conflict:${(c.eventIds ?? []).join('-')}`, tuVi: 0, congDuc: 0, nghiepLuc: 1 });
293
+ for (const l of analysis.repetition?.retryLoopCandidates ?? []) out.push({ key: `loop:${l.taskId}`, tuVi: 0, congDuc: 0, nghiepLuc: 1 });
294
+ return out;
295
+ }
296
+
297
+ // Idempotent accumulator. `prior` carries lifetime totals plus a salted
298
+ // seen-ledger; only contributions whose salted key is unseen accrue. Positive
299
+ // gains (Tu Vi, Công Đức) and the state ratios are withheld unless the policy
300
+ // is `clear`; Nghiệp Lực (risk) always accrues.
301
+ export function progressionMetrics(analysis, { prior = null, canGamify = true, salt = '' } = {}) {
302
+ const contributions = progressionContributions(analysis);
303
+ const seen = new Set(prior?.seen ?? []);
304
+ const saltKey = (k) => sha16(`${salt}:${k}`);
305
+ const fresh = contributions.filter((c) => !seen.has(saltKey(c.key)));
306
+ const overlap = contributions.length - fresh.length;
307
+
308
+ const sum = (field) => fresh.reduce((n, c) => n + c[field], 0);
309
+ const windowTuVi = canGamify ? sum('tuVi') : 0;
310
+ const windowCongDuc = canGamify ? sum('congDuc') : 0;
311
+ const windowNghiepLuc = sum('nghiepLuc');
312
+ const hadFresh = fresh.length > 0;
313
+
314
+ const nextSeen = [...seen, ...fresh.map((c) => saltKey(c.key))].sort();
315
+
316
+ // State ratios (not accumulators) — withheld under a non-clear policy.
317
+ const issues = analysis.issues ?? {};
318
+ const passes = issues.passes ?? 0;
319
+ const failures = (issues.failures ?? []).length;
320
+ const recoveries = (issues.recoveries ?? []).length;
321
+ const userPrompts = analysis.coverage?.userPrompts ?? 0;
322
+ const retryPrompts = (analysis.repetition?.retryLoopCandidates ?? []).reduce((n, l) => n + l.count, 0);
323
+ const ratio = (v) => (canGamify ? round3(clamp01(v)) : null);
324
+
325
+ return {
326
+ tuVi: { window: windowTuVi, lifetime: (prior?.tuVi?.lifetime ?? 0) + windowTuVi },
327
+ daoHanh: { windows: (prior?.daoHanh?.windows ?? 0) + (hadFresh ? 1 : 0) },
328
+ ngoTinh: ratio(0.5 + 0.5 * (failures ? recoveries / failures : 0.5) - 0.3 * (userPrompts ? retryPrompts / userPrompts : 0)),
329
+ doThuanThuc: canGamify
330
+ ? { overall: round3(clamp01(passes + failures === 0 ? 0.3 : (passes + recoveries) / (passes + failures + 1))), note: { vi: 'V1 đo mức thuần thục tổng; thuần thục theo từng đạo tu cần bằng chứng gắn theo path.', en: 'V1 tracks overall mastery; per-path mastery needs path-tagged evidence.' } }
331
+ : null,
332
+ tamCanh: ratio(failures === 0 ? 0.7 : recoveries / failures),
333
+ congDuc: { window: windowCongDuc, lifetime: (prior?.congDuc?.lifetime ?? 0) + windowCongDuc },
334
+ nghiepLuc: { window: windowNghiepLuc, lifetime: (prior?.nghiepLuc?.lifetime ?? 0) + windowNghiepLuc },
335
+ seen: nextSeen,
336
+ overlap
337
+ };
338
+ }
@@ -0,0 +1,126 @@
1
+ // Parses a /tutien invocation. The skill is user-invoked only
2
+ // (disable-model-invocation: true), so nothing here runs unless the user
3
+ // typed /tutien. `off`/`on` toggle the session mode; a report action only
4
+ // runs when the mode is on.
5
+
6
+ const ACTIONS = new Set(['on', 'off', 'status', 'preview', 'analyze', 'compare', 'explain', 'classify']);
7
+ const TONE_ALIASES = new Map([
8
+ ['serene', 'serene'],
9
+ ['spirited', 'spirited'],
10
+ ['neutral', 'neutral'],
11
+ // Backward-compatible aliases. They are accepted but no longer advertised,
12
+ // keeping the public vocabulary calm and unambiguous across agent surfaces.
13
+ ['gentle', 'serene'],
14
+ ['spicy', 'spirited']
15
+ ]);
16
+ const STORY_LANGUAGES = new Set(['auto', 'vi', 'en', 'zh']);
17
+ const STORY_STYLES = new Set(['auto', 'classic-quest', 'web-serial', 'daily-life', 'clan-epic', 'comic-adventure']);
18
+ const STORY_FOCUSES = new Set(['balanced', 'project', 'characters', 'world', 'sect-politics']);
19
+
20
+ const allowedOr = (value, allowed, fallback) => allowed.has(String(value).toLowerCase()) ? String(value).toLowerCase() : fallback;
21
+ export const normalizeStoryLanguage = (value) => allowedOr(value, STORY_LANGUAGES, 'auto');
22
+ export const normalizeStoryStyle = (value) => allowedOr(value, STORY_STYLES, 'auto');
23
+ export const normalizeStoryFocus = (value) => allowedOr(value, STORY_FOCUSES, 'balanced');
24
+
25
+ export const TUTIEN_EXPERIENCE = Object.freeze({
26
+ kind: 'wholesome-coding-classification-game',
27
+ purpose: 'stress-relief-and-mindful-reflection',
28
+ narrativeStyle: 'refined-mystical-xianxia',
29
+ semanticNamespace: 'tutien-coding-cultivation-v1'
30
+ });
31
+
32
+ const STOP_REQUESTS = [
33
+ /^(?:(?:please\s+)|(?:(?:can|could|would)\s+you\s+(?:please\s+)?))?(?:off|stop|end|exit|disable)(?:\s+(?:now|please))?[.!]?$/i,
34
+ /^(?:(?:please\s+)|(?:(?:can|could|would)\s+you\s+(?:please\s+)?))?(?:stop|end|exit|disable)\s+(?:\/?tutien|tu\s+tien)(?:\s+mode)?(?:\s+(?:now|please))?[.!]?$/i,
35
+ /^(?:(?:vui\s+lòng|hãy|giúp\s+tôi)\s+)?(?:dừng|tắt|kết\s+thúc|thoát)(?:\s+(?:nhé|ngay))?[.!]?$/iu,
36
+ /^(?:(?:vui\s+lòng|hãy|giúp\s+tôi)\s+)?(?:dừng|tắt|kết\s+thúc|thoát)\s+(?:\/?tutien|tu\s+tiên)(?:\s+(?:mode|chế\s+độ))?(?:\s+(?:nhé|ngay))?[.!]?$/iu
37
+ ];
38
+
39
+ export function normalizeTone(value) {
40
+ return TONE_ALIASES.get(String(value ?? '').toLowerCase()) ?? 'serene';
41
+ }
42
+
43
+ export function isStopRequest(argsString = '') {
44
+ const normalized = String(argsString).trim().replace(/\s+/g, ' ');
45
+ return STOP_REQUESTS.some((re) => re.test(normalized));
46
+ }
47
+
48
+ export function parseInvocation(argsString = '') {
49
+ const tokens = String(argsString).trim().split(/\s+/).filter(Boolean);
50
+ const options = {
51
+ scope: 'repo',
52
+ privacy: 'aggregate-only',
53
+ language: 'auto',
54
+ tone: 'serene',
55
+ villains: 'on',
56
+ score: 'hidden',
57
+ includeExcerpts: false,
58
+ range: 'all',
59
+ sources: [],
60
+ story: 'on',
61
+ storyLanguage: 'auto',
62
+ storyStyle: 'auto',
63
+ storyFocus: 'balanced',
64
+ output: 'brief'
65
+ };
66
+ const providedOptions = new Set();
67
+ let action = null;
68
+
69
+ // A direct request to end the experience always wins over report parsing.
70
+ // This keeps prose mode and approval state from lingering after the user
71
+ // asks to return to the kit's normal voice.
72
+ if (isStopRequest(argsString)) {
73
+ return { action: 'off', isModeToggle: true, explicitAction: true, options, providedOptions: [] };
74
+ }
75
+
76
+ for (const tok of tokens) {
77
+ const eq = tok.indexOf('=');
78
+ if (eq === -1) {
79
+ if (!action && ACTIONS.has(tok)) action = tok;
80
+ continue;
81
+ }
82
+ const key = tok.slice(0, eq);
83
+ const value = tok.slice(eq + 1);
84
+ switch (key) {
85
+ case 'language': providedOptions.add(key); options.language = value; break;
86
+ case 'tone': providedOptions.add(key); options.tone = normalizeTone(value); break;
87
+ case 'villains': providedOptions.add(key); options.villains = value === 'off' ? 'off' : 'on'; break;
88
+ case 'score': providedOptions.add(key); options.score = value === 'show' ? 'show' : 'hidden'; break;
89
+ case 'scope': providedOptions.add(key); options.scope = value; break;
90
+ case 'privacy': providedOptions.add(key); options.privacy = value; break;
91
+ case 'range': providedOptions.add(key); options.range = value; break;
92
+ case 'include-excerpts': providedOptions.add(key); options.includeExcerpts = value === 'true'; break;
93
+ case 'sources': providedOptions.add(key); options.sources = value.split(',').filter(Boolean); break;
94
+ case 'previous': providedOptions.add(key); options.previous = value; break;
95
+ case 'metric': providedOptions.add(key); options.metric = value; break;
96
+ case 'approve': providedOptions.add(key); options.approve = value; break;
97
+ case 'snapshot': providedOptions.add(key); options.snapshot = value === 'true'; break;
98
+ case 'faction': providedOptions.add(key); options.faction = value; break;
99
+ case 'affiliation': providedOptions.add(key); options.affiliation = value; break;
100
+ case 'paths': providedOptions.add(key); options.paths = value.split(',').filter(Boolean); break;
101
+ case 'domains': providedOptions.add(key); options.domains = value.split(',').filter(Boolean); break;
102
+ case 'authorization': providedOptions.add(key); options.authorization = value; break;
103
+ case 'story': providedOptions.add(key); options.story = value === 'off' ? 'off' : 'on'; break;
104
+ case 'story-language': providedOptions.add(key); options.storyLanguage = normalizeStoryLanguage(value); break;
105
+ case 'story-style': providedOptions.add(key); options.storyStyle = normalizeStoryStyle(value); break;
106
+ case 'story-focus': providedOptions.add(key); options.storyFocus = normalizeStoryFocus(value); break;
107
+ case 'output': providedOptions.add(key); options.output = value === 'ledger' ? 'ledger' : 'brief'; break;
108
+ default: break;
109
+ }
110
+ }
111
+
112
+ // Default action when the user typed only `/tutien`: a safe preview. A bare
113
+ // invocation (no explicit action word) also re-activates the mode; an
114
+ // explicit report action while the mode is off is refused by the runner.
115
+ const explicitAction = action !== null;
116
+ if (!action) action = 'preview';
117
+ const isModeToggle = action === 'on' || action === 'off' || action === 'status';
118
+ return { action, isModeToggle, explicitAction, options, providedOptions: [...providedOptions] };
119
+ }
120
+
121
+ // The livelier `spirited` voice is explicit opt-in. Safety-sensitive contexts
122
+ // always use neutral prose. Legacy tone names normalize to the new namespace.
123
+ export function resolveTone(requestedTone, { sensitive = false } = {}) {
124
+ if (sensitive) return 'neutral';
125
+ return normalizeTone(requestedTone);
126
+ }