@anh3d0nic/qwen-code-termux-ice 16.0.4 → 16.0.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 (69) hide show
  1. package/bin/qwen-ice +25 -5
  2. package/package.json +6 -5
  3. package/scripts/build.js +88 -0
  4. package/scripts/build_package.js +37 -0
  5. package/scripts/build_sandbox.js +174 -0
  6. package/scripts/build_vscode_companion.js +30 -0
  7. package/scripts/check-build-status.js +148 -0
  8. package/scripts/check-i18n.ts +462 -0
  9. package/scripts/check-lockfile.js +74 -0
  10. package/scripts/clean.js +59 -0
  11. package/scripts/copy_bundle_assets.js +90 -0
  12. package/scripts/copy_files.js +86 -0
  13. package/scripts/create_alias.sh +39 -0
  14. package/scripts/dev.js +109 -0
  15. package/scripts/esbuild-shims.js +29 -0
  16. package/scripts/generate-git-commit-info.js +71 -0
  17. package/scripts/generate-settings-schema.ts +146 -0
  18. package/scripts/get-release-version.js +411 -0
  19. package/scripts/ice-mobile.js +5 -0
  20. package/scripts/ice-session.js +6 -0
  21. package/scripts/ice-skills.js +31 -0
  22. package/scripts/ice-teams.js +34 -0
  23. package/scripts/ice-v10.js +276 -0
  24. package/scripts/ice-v11.js +276 -0
  25. package/scripts/ice-v12.js +568 -0
  26. package/scripts/ice-v13.js +824 -0
  27. package/scripts/ice-v14.js +1059 -0
  28. package/scripts/ice-v15.js +1501 -0
  29. package/scripts/ice-v2.js +26 -0
  30. package/scripts/ice-v3-core.js +261 -0
  31. package/scripts/ice-v3.js +46 -0
  32. package/scripts/ice-v4.js +657 -0
  33. package/scripts/ice-v5.js +371 -0
  34. package/scripts/ice-v6.js +305 -0
  35. package/scripts/ice-v7.js +291 -0
  36. package/scripts/ice-v8.js +550 -0
  37. package/scripts/ice-v9.js +546 -0
  38. package/scripts/install-ice.sh +70 -0
  39. package/scripts/install.sh +136 -0
  40. package/scripts/installation/INSTALLATION_GUIDE.md +250 -0
  41. package/scripts/installation/install-qwen-with-source.bat +302 -0
  42. package/scripts/installation/install-qwen-with-source.sh +570 -0
  43. package/scripts/lint.js +205 -0
  44. package/scripts/local_telemetry.js +219 -0
  45. package/scripts/postinstall.cjs +235 -0
  46. package/scripts/pre-commit.js +22 -0
  47. package/scripts/prepare-package.js +186 -0
  48. package/scripts/prepare-termux.cjs +26 -0
  49. package/scripts/sandbox_command.js +128 -0
  50. package/scripts/start.js +86 -0
  51. package/scripts/telemetry.js +85 -0
  52. package/scripts/telemetry_gcp.js +188 -0
  53. package/scripts/telemetry_utils.js +450 -0
  54. package/scripts/test-v10.js +18 -0
  55. package/scripts/test-v11.js +18 -0
  56. package/scripts/test-v12.js +18 -0
  57. package/scripts/test-v13.js +18 -0
  58. package/scripts/test-v14.js +18 -0
  59. package/scripts/test-v3.js +47 -0
  60. package/scripts/test-v4.js +47 -0
  61. package/scripts/test-v6.js +59 -0
  62. package/scripts/test-v8.js +42 -0
  63. package/scripts/test-v9.js +18 -0
  64. package/scripts/test-windows-paths.js +51 -0
  65. package/scripts/tests/get-release-version.test.js +186 -0
  66. package/scripts/tests/test-setup.ts +12 -0
  67. package/scripts/tests/vitest.config.ts +26 -0
  68. package/scripts/unused-keys-only-in-locales.json +62 -0
  69. package/scripts/version.js +112 -0
@@ -0,0 +1,546 @@
1
+ #!/usr/bin/env node
2
+
3
+ /**
4
+ * ❄️ ICE v9.0.0 - Self-Improving Termux Specialist
5
+ *
6
+ * NEW SYSTEMS:
7
+ * 1. Self-Critique Loop - Attack first draft, fix, then send
8
+ * 2. Adversarial Code Testing - 3 break inputs, fix all
9
+ * 3. Domain Memory - Persistent learning across sessions
10
+ * 4. Confidence Gating - Never fake confidence
11
+ * 5. Intent Ladder - SURFACE → REAL → DEEP
12
+ * 6. Termux Specialist Layer - Hardcoded Termux knowledge
13
+ */
14
+
15
+ import { readFileSync, writeFileSync, existsSync, mkdirSync, appendFileSync } from 'node:fs';
16
+ import { join } from 'node:path';
17
+
18
+ const SESSION_FILE = join(process.env.HOME, '.qwen', 'ice_session.json');
19
+ const CONTEXT_FILE = join(process.env.HOME, '.qwen', 'ice_active_context.json');
20
+ const MEMORY_FILE = join(process.env.HOME, '.qwen', 'session_memory.json');
21
+ const TERMUX = {
22
+ PREFIX: '/data/data/com.termux/files/usr',
23
+ HOME: '/data/data/com.termux/files/home',
24
+ NO_SUDO: true,
25
+ ARM64: true,
26
+ PKG_MANAGER: 'pkg',
27
+ PYTHON_FLAGS: '--break-system-packages'
28
+ };
29
+
30
+ // ============================================
31
+ // SYSTEM 3 — DOMAIN MEMORY (PERSISTENT LEARNING)
32
+ // ============================================
33
+
34
+ class DomainMemory {
35
+ constructor() {
36
+ this.memory = {
37
+ user_patterns: [],
38
+ known_errors: [],
39
+ project_state: {},
40
+ user_preferences: []
41
+ };
42
+ this.load();
43
+ }
44
+
45
+ load() {
46
+ if (existsSync(MEMORY_FILE)) {
47
+ try {
48
+ this.memory = JSON.parse(readFileSync(MEMORY_FILE, 'utf-8'));
49
+ } catch (e) { this.memory = { user_patterns: [], known_errors: [], project_state: {}, user_preferences: [] }; }
50
+ }
51
+ }
52
+
53
+ save() {
54
+ const dir = join(process.env.HOME, '.qwen');
55
+ if (!existsSync(dir)) mkdirSync(dir, { recursive: true });
56
+ writeFileSync(MEMORY_FILE, JSON.stringify(this.memory, null, 2));
57
+ }
58
+
59
+ addPattern(pattern) {
60
+ if (!this.memory.user_patterns.includes(pattern)) {
61
+ this.memory.user_patterns.push(pattern);
62
+ this.save();
63
+ }
64
+ }
65
+
66
+ addError(error, fix) {
67
+ this.memory.known_errors.push({ error, fix, timestamp: Date.now() });
68
+ if (this.memory.known_errors.length > 20) this.memory.known_errors.shift();
69
+ this.save();
70
+ }
71
+
72
+ updateProjectState(key, value) {
73
+ this.memory.project_state[key] = value;
74
+ this.save();
75
+ }
76
+
77
+ addPreference(pref) {
78
+ if (!this.memory.user_preferences.includes(pref)) {
79
+ this.memory.user_preferences.push(pref);
80
+ this.save();
81
+ }
82
+ }
83
+
84
+ get() { return this.memory; }
85
+
86
+ clear() {
87
+ this.memory = { user_patterns: [], known_errors: [], project_state: {}, user_preferences: [] };
88
+ this.save();
89
+ }
90
+ }
91
+
92
+ // ============================================
93
+ // SYSTEM 1 — SELF-CRITIQUE LOOP
94
+ // ============================================
95
+
96
+ class SelfCritiqueLoop {
97
+ constructor() {
98
+ this.critiqueQuestions = [
99
+ 'What is wrong with this?',
100
+ 'What did I miss?',
101
+ 'Where could this break?',
102
+ 'Is this Termux-compatible?',
103
+ 'Are there edge cases unhandled?',
104
+ 'Is this the simplest solution?'
105
+ ];
106
+ }
107
+
108
+ critique(draft) {
109
+ const issues = [];
110
+
111
+ // Check for common problems
112
+ if (draft.includes('sudo')) issues.push('❌ Uses sudo (not available on Termux)');
113
+ if (draft.includes('/usr/bin') || draft.includes('/bin/')) issues.push('❌ Hardcoded paths (will fail on Termux)');
114
+ if (draft.length < 50) issues.push('⚠️ Response too short - may be incomplete');
115
+ if (!draft.includes('try') && !draft.includes('if') && draft.includes('function')) issues.push('⚠️ No error handling');
116
+ if (draft.includes('TODO') || draft.includes('FIXME')) issues.push('⚠️ Contains unresolved placeholders');
117
+
118
+ return issues;
119
+ }
120
+
121
+ fix(draft, issues) {
122
+ let fixed = draft;
123
+
124
+ issues.forEach(issue => {
125
+ if (issue.includes('sudo')) fixed = fixed.replace(/sudo\s+/g, '# sudo not available on Termux\n');
126
+ if (issue.includes('Hardcoded paths')) {
127
+ fixed = fixed.replace(/\/usr\/bin\//g, `${TERMUX.PREFIX}/bin/`);
128
+ fixed = fixed.replace(/\/bin\//g, `${TERMUX.PREFIX}/bin/`);
129
+ }
130
+ });
131
+
132
+ return fixed;
133
+ }
134
+
135
+ process(draft) {
136
+ console.log('\n🔍 Self-Critique Loop\n');
137
+ console.log('Draft generated. Attacking...\n');
138
+
139
+ const issues = this.critique(draft);
140
+
141
+ if (issues.length === 0) {
142
+ console.log('✅ No issues found in draft\n');
143
+ return draft;
144
+ }
145
+
146
+ console.log('Issues found:');
147
+ issues.forEach((i, n) => console.log(` ${n + 1}. ${i}`));
148
+ console.log();
149
+
150
+ const fixed = this.fix(draft, issues);
151
+ console.log('✅ Fixed issues. Final version:\n');
152
+
153
+ return fixed;
154
+ }
155
+ }
156
+
157
+ // ============================================
158
+ // SYSTEM 2 — ADVERSARIAL CODE TESTING
159
+ // ============================================
160
+
161
+ class AdversarialCodeTest {
162
+ constructor() {
163
+ this.termuxConstraints = [
164
+ { name: 'No sudo', test: code => !code.includes('sudo') },
165
+ { name: 'No /usr/bin', test: code => !code.includes('/usr/bin/') && !code.includes('/bin/bash') },
166
+ { name: 'Error handling', test: code => code.includes('try') || code.includes('if') },
167
+ { name: 'No systemd', test: code => !code.includes('systemctl') && !code.includes('systemd') }
168
+ ];
169
+ }
170
+
171
+ generateBreakInputs(task) {
172
+ return [
173
+ { name: 'Empty input', input: '', description: 'What if input is empty?' },
174
+ { name: 'Malformed input', input: 'null/undefined/NaN', description: 'What if input is malformed?' },
175
+ { name: 'Extreme input', input: 'A'.repeat(10000), description: 'What if input is extremely large?' }
176
+ ];
177
+ }
178
+
179
+ testCode(code, task) {
180
+ console.log('\n⚔️ Adversarial Code Testing\n');
181
+ console.log('Code generated. Creating break inputs...\n');
182
+
183
+ const attacks = this.generateBreakInputs(task);
184
+ const failures = [];
185
+
186
+ attacks.forEach((attack, n) => {
187
+ console.log(`Attack ${n + 1}: ${attack.name}`);
188
+ console.log(` Description: ${attack.description}`);
189
+ console.log(` Input: "${attack.input.substring(0, 30)}${attack.input.length > 30 ? '...' : ''}"`);
190
+
191
+ // Check if code handles this
192
+ const handlesEmpty = code.includes('if (!') || code.includes('if (') || code.includes('?.');
193
+ const handlesType = code.includes('typeof') || code.includes('Number(') || code.includes('String(');
194
+
195
+ if (attack.name === 'Empty input' && !handlesEmpty) {
196
+ failures.push(`❌ Does not handle empty input`);
197
+ } else if (attack.name === 'Malformed input' && !handlesType) {
198
+ failures.push(`❌ Does not validate input type`);
199
+ } else {
200
+ console.log(' ✅ Code handles this case\n');
201
+ }
202
+ });
203
+
204
+ // Termux constraint checks
205
+ console.log('\nTermux Constraint Checks:');
206
+ this.termuxConstraints.forEach(c => {
207
+ const passes = c.test(code);
208
+ console.log(` ${passes ? '✅' : '❌'} ${c.name}`);
209
+ if (!passes) failures.push(`❌ Fails: ${c.name}`);
210
+ });
211
+
212
+ console.log();
213
+ return { passes: failures.length === 0, failures };
214
+ }
215
+
216
+ fixCode(code, failures) {
217
+ let fixed = code;
218
+
219
+ failures.forEach(f => {
220
+ if (f.includes('empty input')) {
221
+ fixed = ' if (!input) throw new Error("Input required");\n' + fixed;
222
+ }
223
+ if (f.includes('input type')) {
224
+ fixed = ' if (typeof input !== "string") throw new TypeError("Expected string");\n' + fixed;
225
+ }
226
+ if (f.includes('sudo')) {
227
+ fixed = fixed.replace(/sudo\s+/g, '');
228
+ }
229
+ if (f.includes('/usr/bin')) {
230
+ fixed = fixed.replace(/\/usr\/bin\//g, `${TERMUX.PREFIX}/bin/`);
231
+ }
232
+ });
233
+
234
+ return fixed;
235
+ }
236
+
237
+ process(code, task) {
238
+ const result = this.testCode(code, task);
239
+
240
+ if (!result.passes) {
241
+ console.log('❌ Code failed adversarial testing. Fixing...\n');
242
+ return this.fixCode(code, result.failures);
243
+ }
244
+
245
+ console.log('✅ Code passed all adversarial tests\n');
246
+ return code;
247
+ }
248
+ }
249
+
250
+ // ============================================
251
+ // SYSTEM 4 — CONFIDENCE GATING
252
+ // ============================================
253
+
254
+ class ConfidenceGating {
255
+ constructor() {
256
+ this.thresholds = {
257
+ CERTAIN: { min: 90, action: 'respond_directly' },
258
+ LIKELY: { min: 70, action: 'respond_with_assumption_flag' },
259
+ UNCERTAIN: { min: 0, action: 'ask_clarifying_question' }
260
+ };
261
+ }
262
+
263
+ calculateConfidence(query, context) {
264
+ let confidence = 50; // Base confidence
265
+
266
+ // Boost for specific patterns
267
+ if (query.includes('how to') || query.includes('how do I')) confidence += 20;
268
+ if (query.includes('fix') || query.includes('error')) confidence += 15;
269
+ if (query.includes('termux') || query.includes('android')) confidence += 15;
270
+
271
+ // Reduce for vague queries
272
+ if (query.length < 10) confidence -= 20;
273
+ if (query.includes('maybe') || query.includes('not sure')) confidence -= 15;
274
+ if (query.endsWith('?')) confidence -= 5; // Questions are less certain
275
+
276
+ // Boost with context
277
+ if (context && context.goal) confidence += 10;
278
+
279
+ return Math.min(100, Math.max(0, confidence));
280
+ }
281
+
282
+ getLevel(confidence) {
283
+ if (confidence >= this.thresholds.CERTAIN.min) return 'CERTAIN';
284
+ if (confidence >= this.thresholds.LIKELY.min) return 'LIKELY';
285
+ return 'UNCERTAIN';
286
+ }
287
+
288
+ gate(query, context) {
289
+ const confidence = this.calculateConfidence(query, context);
290
+ const level = this.getLevel(confidence);
291
+
292
+ console.log('\n🎯 Confidence Gating\n');
293
+ console.log(`Confidence: ${confidence}%`);
294
+ console.log(`Level: ${level}\n`);
295
+
296
+ if (level === 'UNCERTAIN') {
297
+ console.log('❓ Need clarification before proceeding.\n');
298
+ console.log('Suggested questions:');
299
+ console.log(' 1. What is your specific goal?');
300
+ console.log(' 2. What have you tried so far?');
301
+ console.log(' 3. What error messages are you seeing?\n');
302
+ } else if (level === 'LIKELY') {
303
+ console.log('⚠️ Proceeding with assumptions. Please correct if wrong.\n');
304
+ } else {
305
+ console.log('✅ High confidence. Proceeding.\n');
306
+ }
307
+
308
+ return { confidence, level, action: this.thresholds[level].action };
309
+ }
310
+ }
311
+
312
+ // ============================================
313
+ // SYSTEM 5 — INTENT LADDER
314
+ // ============================================
315
+
316
+ class IntentLadder {
317
+ classify(query) {
318
+ const surface = query;
319
+
320
+ // Extract REAL intent
321
+ let real = surface;
322
+ if (surface.includes('how to')) real = 'User needs step-by-step instructions';
323
+ else if (surface.includes('why')) real = 'User needs root cause explanation';
324
+ else if (surface.includes('fix') || surface.includes('error')) real = 'User needs working solution';
325
+ else if (surface.includes('best') || surface.includes('recommended')) real = 'User needs expert recommendation';
326
+
327
+ // Extract DEEP intent
328
+ let deep = real;
329
+ if (real.includes('instructions')) deep = 'User wants to learn and become self-sufficient';
330
+ if (real.includes('root cause')) deep = 'User wants to understand system to prevent future issues';
331
+ if (real.includes('working solution')) deep = 'User wants to ship/complete their project';
332
+ if (real.includes('recommendation')) deep = 'User wants to make informed long-term decision';
333
+
334
+ return { surface, real, deep };
335
+ }
336
+
337
+ process(query) {
338
+ const ladder = this.classify(query);
339
+
340
+ console.log('\n🪜 Intent Ladder\n');
341
+ console.log(`SURFACE: "${ladder.surface}"`);
342
+ console.log(`REAL: ${ladder.real}`);
343
+ console.log(`DEEP: ${ladder.deep}\n`);
344
+
345
+ if (ladder.deep !== ladder.real) {
346
+ console.log('Strategy: Address DEEP intent for long-term success\n');
347
+ }
348
+
349
+ return ladder;
350
+ }
351
+ }
352
+
353
+ // ============================================
354
+ // SYSTEM 6 — TERMUX SPECIALIST LAYER
355
+ // ============================================
356
+
357
+ class TermuxSpecialist {
358
+ constructor() {
359
+ this.knowledge = {
360
+ PREFIX: TERMUX.PREFIX,
361
+ HOME: TERMUX.HOME,
362
+ NO_SUDO: TERMUX.NO_SUDO,
363
+ ARM64: TERMUX.ARM64,
364
+ PKG: TERMUX.PKG_MANAGER,
365
+ PYTHON_FLAGS: TERMUX.PYTHON_FLAGS,
366
+ commonPaths: {
367
+ node: `${TERMUX.PREFIX}/bin/node`,
368
+ python: `${TERMUX.PREFIX}/bin/python`,
369
+ pip: `${TERMUX.PREFIX}/bin/pip`,
370
+ git: `${TERMUX.PREFIX}/bin/git`,
371
+ home: TERMUX.HOME
372
+ },
373
+ packageManager: {
374
+ install: 'pkg install',
375
+ update: 'pkg update && pkg upgrade',
376
+ search: 'pkg search',
377
+ remove: 'pkg uninstall'
378
+ }
379
+ };
380
+ }
381
+
382
+ apply(code) {
383
+ let fixed = code;
384
+
385
+ // Auto-fix common issues
386
+ fixed = fixed.replace(/sudo\s+/g, '# Termux: no sudo needed\n');
387
+ fixed = fixed.replace(/apt-get\s+install/g, 'pkg install');
388
+ fixed = fixed.replace(/apt\s+install/g, 'pkg install');
389
+ fixed = fixed.replace(/\/usr\/local/g, TERMUX.PREFIX);
390
+ fixed = fixed.replace(/\/home\//g, `${TERMUX.HOME}/`);
391
+ fixed = fixed.replace(/pip\s+install/g, `pip install ${TERMUX.PYTHON_FLAGS}`);
392
+ fixed = fixed.replace(/systemctl\s+/g, '# Termux: no systemd\n# ');
393
+ fixed = fixed.replace(/\/bin\/bash/g, `${TERMUX.PREFIX}/bin/bash`);
394
+
395
+ return fixed;
396
+ }
397
+
398
+ validate(code) {
399
+ const issues = [];
400
+
401
+ if (code.includes('sudo')) issues.push('Contains sudo (not available)');
402
+ if (code.includes('apt-get') || code.includes('apt ')) issues.push('Uses apt (use pkg instead)');
403
+ if (code.includes('/usr/local')) issues.push('Wrong prefix (use ${TERMUX.PREFIX})');
404
+ if (code.includes('systemctl')) issues.push('Uses systemd (not available)');
405
+
406
+ return { valid: issues.length === 0, issues };
407
+ }
408
+
409
+ getInfo() {
410
+ return this.knowledge;
411
+ }
412
+ }
413
+
414
+ // ============================================
415
+ // INHERITED FROM v8.0.0
416
+ // ============================================
417
+
418
+ class ActiveContextEngine {
419
+ constructor() {
420
+ this.context = { goal: '', decisions: [], blockers: [], last_action: '', turn_count: 0 };
421
+ this.load();
422
+ }
423
+ load() { if (existsSync(CONTEXT_FILE)) { try { this.context = JSON.parse(readFileSync(CONTEXT_FILE, 'utf-8')); } catch (e) { this.context = { goal: '', decisions: [], blockers: [], last_action: '', turn_count: 0 }; } } }
424
+ save() { writeFileSync(CONTEXT_FILE, JSON.stringify(this.context, null, 2)); }
425
+ update(goal, decision, blocker, action) { if (goal) this.context.goal = goal; if (decision) this.context.decisions.push(decision); if (blocker && !this.context.blockers.includes(blocker)) this.context.blockers.push(blocker); if (action) this.context.last_action = action; this.context.turn_count++; this.compress(); this.save(); }
426
+ compress() { const maxLen = 1000; const json = JSON.stringify(this.context); if (json.length > maxLen) { this.context.decisions = this.context.decisions.slice(-3); this.context.blockers = this.context.blockers.slice(-3); } }
427
+ get() { return this.context; }
428
+ format() { const c = this.context; return `\nACTIVE_CONTEXT:\n goal: ${c.goal || 'not set'}\n decisions: ${c.decisions.length > 0 ? c.decisions.join(', ') : 'none'}\n blockers: ${c.blockers.length > 0 ? c.blockers.join(', ') : 'none'}\n last_action: ${c.last_action || 'none'}\n turn: ${c.turn_count}`; }
429
+ clear() { this.context = { goal: '', decisions: [], blockers: [], last_action: '', turn_count: 0 }; if (existsSync(CONTEXT_FILE)) writeFileSync(CONTEXT_FILE, JSON.stringify(this.context, null, 2)); }
430
+ }
431
+
432
+ class IntentEngine {
433
+ constructor() { this.intentPatterns = [ { literal: /how (to|do i)/i, intent: 'user wants step-by-step instructions', response: 'Provide numbered steps' }, { literal: /why (isn't|doesn't|not)/i, intent: 'user is frustrated, needs root cause', response: 'Explain root cause first' }, { literal: /can you|could you/i, intent: 'user wants action, not permission', response: 'Take action immediately' }, { literal: /what (is|are)|explain/i, intent: 'user needs understanding', response: 'Explain concept, then example' }, { literal: /fix|broken|error|fail/i, intent: 'user needs working solution now', response: 'Provide fix first' }, { literal: /best|optimal|recommended/i, intent: 'user wants expert judgment', response: 'Give recommendation with tradeoffs' }, { literal: /termux|android|mobile/i, intent: 'user on Termux', response: 'Always consider Termux constraints' } ]; }
434
+ analyze(input) { const literal = input; let detected = null; for (const p of this.intentPatterns) { if (p.literal.test(literal)) { detected = p; break; } } return { literal, intent: detected ? detected.intent : 'user needs help', response_strategy: detected ? detected.response : 'Provide clear help', confidence: detected ? 85 : 60 }; }
435
+ }
436
+
437
+ class CodeQualityGate {
438
+ constructor() { this.termuxConstraints = [ `PREFIX = ${TERMUX.PREFIX}`, 'No sudo/root access', 'ARM64 architecture only', 'Limited RAM (2-4GB typical)', 'No systemd or init services', `Storage: ${TERMUX.HOME}`, 'Node.js via pkg install nodejs-lts', 'Python via pkg install python' ]; }
439
+ beforeCode(task) { console.log('\n🔒 Code Quality Gate\n'); console.log('Task: ' + task); console.log('\nTermux Constraints:'); this.termuxConstraints.forEach(c => console.log(' • ' + c)); console.log('\nEdge Cases:'); console.log(' • Permission denied errors\n • Path differences\n • Memory limitations\n • ARM64 binaries\n'); return { task, one_sentence: '', edge_cases: [], termux_constraints: this.termuxConstraints, code: '', verified: false }; }
440
+ verify(code, oneSentence) { console.log('🔍 Verification:'); console.log(' Requirement: ' + oneSentence); console.log(' Code length: ' + code.length + ' chars'); console.log(' Hardcoded paths: ' + (code.includes('/usr/') || code.includes('/bin/') ? '❌ Yes' : '✅ No')); console.log(' Uses sudo: ' + (code.includes('sudo') ? '❌ Yes' : '✅ No')); console.log(' Error handling: ' + (code.includes('try') || code.includes('catch') || code.includes('if') ? '✅ Yes' : '⚠️ Partial')); console.log(); return !code.includes('sudo') && !code.includes('/usr/bin/') && !code.includes('/bin/'); }
441
+ }
442
+
443
+ function detectMobile() { const isTermux = !!process.env.TERMUX_VERSION; const columns = process.stdout.columns || 80; return { isTermux, isSmallScreen: columns < 80, columns }; }
444
+ function formatMobileResponse(content) { const maxLength = 500; console.log('\n📱 Mobile Mode\n'); console.log('─'.repeat(Math.min(60, process.stdout.columns || 60))); if (content.length > maxLength) { console.log(content.substring(0, maxLength) + '...'); console.log('\n⋯ Full response in desktop mode'); } else { console.log(content); } console.log('─'.repeat(Math.min(60, process.stdout.columns || 60))); }
445
+ function formatDesktopResponse(content) { console.log('\n💻 Desktop Mode\n'); console.log('═'.repeat(80)); console.log(content); console.log('═'.repeat(80)); }
446
+ function formatResponse(content) { const device = detectMobile(); if (device.isSmallScreen || device.isTermux) { formatMobileResponse(content); } else { formatDesktopResponse(content); } }
447
+
448
+ const THEMES = { amoled: { bg: '#000000', fg: '#E0E0E0', accent: '#00E676', error: '#FF5252' }, termux: { bg: '#000000', fg: '#FFFFFF', accent: '#00FF00', error: '#FF0000' } };
449
+ function hexToRgb(hex) { const result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex); return result ? [parseInt(result[1], 16), parseInt(result[2], 16), parseInt(result[3], 16)] : [255, 255, 255]; }
450
+ function applyTheme(themeName = 'amoled') { const theme = THEMES[themeName] || THEMES.amoled; const c = { reset: '\x1b[0m', fg: `\x1b[38;2;${hexToRgb(theme.fg).join(';')}m`, accent: `\x1b[38;2;${hexToRgb(theme.accent).join(';')}m`, error: `\x1b[38;2;${hexToRgb(theme.error).join(';')}m`, bg: `\x1b[48;2;${hexToRgb(theme.bg).join(';')}m` }; console.log(`${c.bg}${c.fg}\n🎨 Theme: ${themeName}\n─`.repeat(40)); console.log(`${c.accent}✓ Accent${c.reset} ${c.error}✗ Error${c.reset}`); console.log(`─`.repeat(40) + `${c.reset}`); }
451
+
452
+ class SessionManager {
453
+ constructor() { const dir = join(process.env.HOME, '.qwen'); if (!existsSync(dir)) mkdirSync(dir, { recursive: true }); }
454
+ save(data = {}) { const session = { timestamp: Date.now(), conversation: data.conversation || [], context: data.context || {} }; try { writeFileSync(SESSION_FILE, JSON.stringify(session, null, 2)); console.log('💾 Session saved'); } catch (e) { console.log('⚠️ Could not save session'); } }
455
+ restore() { if (!existsSync(SESSION_FILE)) { console.log('ℹ️ No previous session'); return null; } try { const s = JSON.parse(readFileSync(SESSION_FILE, 'utf-8')); const age = Math.floor((Date.now() - s.timestamp) / (1000 * 60 * 60)); console.log(`📋 Found session (${age}h ago, ${s.conversation.length} messages)`); return s; } catch (e) { console.log('⚠️ Could not restore'); return null; } }
456
+ clear() { if (existsSync(SESSION_FILE)) { writeFileSync(SESSION_FILE, JSON.stringify({ timestamp: Date.now(), conversation: [] }, null, 2)); console.log('🗑️ Session cleared'); } }
457
+ }
458
+
459
+ const CONTEXT_RULES = [ { id: 'SEC-001', name: 'SQL Injection', severity: 'CRITICAL', pattern: /['"]SELECT.*\+.*['"]/i, skip_if: [/prisma\./i, /sequelize\./i, /typeorm\./i, /knex\./i, /\.query\(\?/i], fix: 'Use parameterized queries' }, { id: 'SEC-002', name: 'XSS via innerHTML', severity: 'HIGH', pattern: /innerHTML\s*=/i, skip_if: [], fix: 'Use textContent or DOMPurify' }, { id: 'SEC-003', name: 'Hardcoded Secret', severity: 'CRITICAL', pattern: /(password|secret|api[_-]?key|token)\s*=\s*["'][^"']+["']/i, skip_if: [/process\.env/i, /config\./i, /\.test\./i], fix: 'Use environment variables' }, { id: 'PERF-001', name: 'N+1 Query', severity: 'HIGH', pattern: /for\s*\(.*\)\s*\{[^}]*\.(find|get|query)/i, skip_if: [/\.include\(/i, /\.join\(/i], fix: 'Use eager loading' } ];
460
+ function contextValidate(code, filePath = '') { console.log('🎯 Context-Aware Validation\n'); const issues = []; CONTEXT_RULES.forEach(rule => { if (!rule.pattern.test(code)) return; const skip = rule.skip_if.some(p => p.test(code) || p.test(filePath)); if (skip) { console.log(` ⏭️ Skipped ${rule.id}: Safe context detected`); return; } issues.push(rule); }); if (issues.length > 0) { console.log(`\n⚠️ Found ${issues.length} issues:\n`); issues.forEach(i => console.log(` 🔴 ${i.id}: ${i.name} (${i.severity})\n 💡 ${i.fix}\n`)); } else { console.log('\n ✅ No issues detected\n'); } return issues; }
461
+
462
+ const PUSHBACK_TRIGGERS = [ { pattern: /SELECT.*FROM.*\+.*user/i, problem: 'SQL Injection', why: 'Attackers can steal your database', fix: 'Use parameterized queries', blocking: true }, { pattern: /password\s*=\s*["'][^"']+["']/i, problem: 'Hardcoded Password', why: 'Passwords in code get committed to git', fix: 'Use process.env.PASSWORD', blocking: true }, { pattern: /eval\s*\(/i, problem: 'eval() Usage', why: 'Arbitrary code execution risk', fix: 'Use JSON.parse()', blocking: true }, { pattern: /while\s*\(true\)/i, problem: 'Infinite Loop', why: 'Will crash your server', fix: 'Add exit condition', blocking: true } ];
463
+ function pushback(code) { console.log('🛑 Pushback Mode\n'); const triggers = PUSHBACK_TRIGGERS.filter(t => t.pattern.test(code)); if (triggers.length === 0) { console.log(' ✅ No critical issues\n'); return { blocked: false }; } console.log('⚠️ I need to push back:\n'); triggers.forEach((t, i) => console.log(`${i + 1}. ${t.problem} (${t.blocking ? 'BLOCKING' : 'WARNING'})\n Why: ${t.why}\n Fix: ${t.fix}\n`)); const blocked = triggers.some(t => t.blocking); if (blocked) console.log('❌ Cannot proceed with this request.\n'); return { blocked, triggers }; }
464
+
465
+ function honestMode(confidence = 0.5, reasons = []) { console.log('🤷 Honest Limitations\n'); if (confidence < 0.6) { console.log(`⚠️ Confidence: ${(confidence * 100).toFixed(0)}%\n`); if (reasons.length > 0) { console.log('Reasons:'); reasons.forEach(r => console.log(` - ${r}`)); } console.log('\nPlease verify before production use.\n'); return { uncertain: true }; } console.log('✅ Confidence is high\n'); return { uncertain: false }; }
466
+
467
+ function fourLayerValidate(code) { console.log('🛡️ Four-Layer Validation\n'); console.log('1️⃣ Security...'); const sec = [{ p: /['"]SELECT.*\+.*['"]/i, n: 'SQL Injection' }, { p: /innerHTML\s*=/i, n: 'XSS' }, { p: /(password|secret|api[_-]?key)\s*=\s*["']/i, n: 'Hardcoded Secret' }].filter(c => c.p.test(code)); console.log(` ${sec.length === 0 ? '✅' : '❌'} ${sec.length === 0 ? 'Pass' : sec.map(i => i.n).join(', ')}`); console.log('2️⃣ Architecture...'); const arch = (code.split('\n').length < 100 && (code.match(/def /g) || []).length > 10) ? ['God Function'] : []; console.log(` ${arch.length === 0 ? '✅' : '❌'} ${arch.length === 0 ? 'Pass' : arch.join(', ')}`); console.log('3️⃣ Performance...'); const perf = [/for.*in.*for/i, /while\s*\(true\)/i].filter(p => p.test(code)).map(() => 'Issue'); console.log(` ${perf.length === 0 ? '✅' : '❌'} ${perf.length === 0 ? 'Pass' : perf.join(', ')}`); console.log('4️⃣ Maintainability...'); const maint = [code.length > 500 ? 'Long File' : null, !/("""|'''|\/\/)/.test(code) ? 'No Documentation' : null].filter(x => x); console.log(` ${maint.length === 0 ? '✅' : '❌'} ${maint.length === 0 ? 'Pass' : maint.join(', ')}`); const pass = sec.length === 0 && arch.length === 0 && perf.length === 0 && maint.length === 0; console.log(`\n${pass ? '✅' : '❌'} Overall: ${pass ? 'PASS' : 'FAIL'}\n`); return pass; }
468
+
469
+ function detectDebt(code) { console.log('⚠️ Technical Debt Detection\n'); const debts = []; if ((code.match(/def /g) || []).length > 15 && /class /i.test(code)) debts.push({ t: 'God Class', s: 'HIGH', f: 'Split into focused classes' }); if ((code.match(/for /g) || []).length > 5 && !/class /i.test(code)) debts.push({ t: 'Missing Abstraction', s: 'MEDIUM', f: 'Create utility module' }); if (/TODO|FIXME/i.test(code)) debts.push({ t: 'Unresolved Debt', s: 'LOW', f: 'Address or create ticket' }); if (debts.length > 0) { console.log(`Found ${debts.length} items:\n`); debts.forEach(d => console.log(` 🔴 ${d.t} (${d.s})\n 💡 ${d.f}\n`)); } else { console.log(' ✅ No significant debt\n'); } return debts; }
470
+
471
+ function showMobileUI() { const device = detectMobile(); console.log('\n❄️ ICE v9.0 - Self-Improving Termux Specialist\n'); if (device.isSmallScreen) { console.log('┌────────────────────────────────┐\n│ ICE v9.0 │ 📱 Mobile │ ^q Quit │\n└────────────────────────────────┘\n\nType your message:\n┌────────────────────────────────┐\n│ > _ │\n└────────────────────────────────┘\nShortcuts: ^s Send ^c Clear\n'); } else { console.log('╔════════════════════════════════════════╗\n║ ICE v9.0 │ 💻 Desktop │ :q Quit ║\n╠════════════════════════════════════════╣\n║ Type your message: ║\n║ > _ ║\n╚════════════════════════════════════════╝\nShortcuts: :w Save :r Regenerate :c Clear\n'); } }
472
+
473
+ // ============================================
474
+ // NEW SYSTEMS DEMO
475
+ // ============================================
476
+
477
+ function demoSelfCritique(draft) { const loop = new SelfCritiqueLoop(); return loop.process(draft); }
478
+ function demoAdversarialTest(code, task) { const test = new AdversarialCodeTest(); return test.process(code, task); }
479
+ function demoDomainMemory() { const mem = new DomainMemory(); mem.addPattern('user prefers concise responses'); mem.addError('sudo not available', 'use pkg instead'); mem.updateProjectState('status', 'active'); console.log('\n💾 Domain Memory\n'); console.log('Patterns:', mem.get().user_patterns); console.log('Known Errors:', mem.get().known_errors.length); console.log('Project State:', mem.get().project_state); console.log(); return mem.get(); }
480
+ function demoConfidenceGate(query) { const gate = new ConfidenceGating(); return gate.gate(query, { goal: 'test' }); }
481
+ function demoIntentLadder(query) { const ladder = new IntentLadder(); return ladder.process(query); }
482
+ function demoTermuxSpecialist(code) { const spec = new TermuxSpecialist(); console.log('\n🤖 Termux Specialist Layer\n'); console.log('Applying Termux knowledge...\n'); const fixed = spec.apply(code); const valid = spec.validate(fixed); console.log('Validation:', valid.valid ? '✅ PASS' : '❌ FAIL: ' + valid.issues.join(', ')); console.log(); return fixed; }
483
+
484
+ // ============================================
485
+ // MAIN CLI
486
+ // ============================================
487
+
488
+ const args = process.argv.slice(2);
489
+ const command = args[0];
490
+ const input = args.slice(1).join(' ');
491
+ const sessionManager = new SessionManager();
492
+ const contextEngine = new ActiveContextEngine();
493
+ const intentEngine = new IntentEngine();
494
+ const qualityGate = new CodeQualityGate();
495
+ const domainMemory = new DomainMemory();
496
+ const selfCritique = new SelfCritiqueLoop();
497
+ const adversarialTest = new AdversarialCodeTest();
498
+ const confidenceGate = new ConfidenceGating();
499
+ const intentLadder = new IntentLadder();
500
+ const termuxSpecialist = new TermuxSpecialist();
501
+
502
+ if (!command) {
503
+ console.log('❄️ ICE v9.0 - Self-Improving Termux Specialist\n');
504
+ console.log('NEW in v9.0:');
505
+ console.log(' 🔁 Self-Critique Loop - Attack first draft, fix, then send');
506
+ console.log(' ⚔️ Adversarial Testing - 3 break inputs, fix all');
507
+ console.log(' 💾 Domain Memory - Persistent learning across sessions');
508
+ console.log(' 🎯 Confidence Gating - Never fake confidence');
509
+ console.log(' 🪜 Intent Ladder - SURFACE → REAL → DEEP');
510
+ console.log(' 🤖 Termux Specialist - Hardcoded Termux knowledge\n');
511
+ console.log('Usage:');
512
+ console.log(' ice-v9 critique [draft] # Self-critique loop');
513
+ console.log(' ice-v9 adversarial [code] # Adversarial testing');
514
+ console.log(' ice-v9 memory [show|clear] # Domain memory');
515
+ console.log(' ice-v9 confidence [query] # Confidence gating');
516
+ console.log(' ice-v9 ladder [query] # Intent ladder');
517
+ console.log(' ice-v9 termux [code] # Termux specialist');
518
+ console.log(' ice-v9 mobile|theme|session|context|intent|gate');
519
+ console.log(' ice-v9 validate|pushback|honest|layers|debt|response\n');
520
+ console.log('Termux Constraints:');
521
+ console.log(' PREFIX=' + TERMUX.PREFIX);
522
+ console.log(' HOME=' + TERMUX.HOME);
523
+ console.log(' No sudo | pkg manager | ARM64 only\n');
524
+ process.exit(0);
525
+ }
526
+
527
+ switch (command) {
528
+ case 'mobile': showMobileUI(); break;
529
+ case 'theme': applyTheme(args[1] || 'amoled'); break;
530
+ case 'session': if (args[1] === 'save') sessionManager.save({ conversation: [] }); else if (args[1] === 'restore') sessionManager.restore(); else if (args[1] === 'clear') sessionManager.clear(); else console.log('Usage: ice-v9 session [save|restore|clear]'); break;
531
+ case 'context': if (args[1] === 'show') { console.log(contextEngine.format() + '\n'); } else if (args[1] === 'clear') { contextEngine.clear(); console.log('🗑️ Context cleared\n'); } else { contextEngine.update('Test goal', 'Test decision', null, input || 'action'); console.log(contextEngine.format() + '\n'); } break;
532
+ case 'intent': intentEngine.analyze(input || 'How do I fix this?'); console.log('Intent:', intentEngine.analyze(input || 'How do I fix this?').intent + '\n'); break;
533
+ case 'validate': contextValidate(input || '// Example code'); break;
534
+ case 'pushback': pushback(input || '// Example code'); break;
535
+ case 'honest': honestMode(0.45, ['Limited context', 'Demo mode']); break;
536
+ case 'layers': fourLayerValidate(input || '// Example code'); break;
537
+ case 'debt': detectDebt(input || '// Example code'); break;
538
+ case 'response': formatResponse(input || 'Test response'); break;
539
+ case 'critique': demoSelfCritique(input || 'function test() { return 1; }'); break;
540
+ case 'adversarial': demoAdversarialTest(input || 'function test(x) { return x; }', 'test function'); break;
541
+ case 'memory': if (args[1] === 'show') demoDomainMemory(); else if (args[1] === 'clear') { domainMemory.clear(); console.log('🗑️ Memory cleared\n'); } else demoDomainMemory(); break;
542
+ case 'confidence': demoConfidenceGate(input || 'How do I fix this error?'); break;
543
+ case 'ladder': demoIntentLadder(input || 'How do I fix this error?'); break;
544
+ case 'termux': demoTermuxSpecialist(input || 'sudo apt-get install python'); break;
545
+ default: console.log(`Unknown command: ${command}`); process.exit(1);
546
+ }
@@ -0,0 +1,70 @@
1
+ #!/data/data/com.termux/files/usr/bin/bash
2
+ # ❄️ ICE v4.3 — Installation Script
3
+ # Qwen Code Termux by @anh3d0nic
4
+ # GitHub: github.com/anh3d0nic/qwen-code-termux-ice
5
+
6
+ set -e
7
+
8
+ echo "❄️ Installing ICE v4.3 — Qwen Code Termux by @anh3d0nic"
9
+ echo "=" | tr -d '\n' && printf '%.0s=' {1..60} && echo
10
+
11
+ ICE_DIR="$HOME/.qwen"
12
+ SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
13
+
14
+ # Create directories
15
+ echo "📁 Creating directories..."
16
+ mkdir -p "$ICE_DIR"
17
+ mkdir -p "$ICE_DIR/ice-memory"
18
+
19
+ # Copy core files
20
+ echo "📦 Copying ICE core files..."
21
+ cp "$SCRIPT_DIR/../.qwen/ice.py" "$ICE_DIR/" 2>/dev/null || echo " (ice.py already exists)"
22
+ cp "$SCRIPT_DIR/../.qwen/qwen.md" "$ICE_DIR/" 2>/dev/null || echo " (qwen.md already exists)"
23
+ cp "$SCRIPT_DIR/../.qwen/ice-auto-load.sh" "$ICE_DIR/" 2>/dev/null || echo " (auto-load already exists)"
24
+
25
+ # Set permissions
26
+ echo "🔒 Setting permissions..."
27
+ chmod 700 "$ICE_DIR/ice-memory"
28
+ chmod +x "$ICE_DIR/ice.py" 2>/dev/null || true
29
+ chmod +x "$ICE_DIR/ice-auto-load.sh" 2>/dev/null || true
30
+
31
+ # Add to bashrc for auto-load
32
+ if ! grep -q "ice-auto-load.sh" "$HOME/.bashrc" 2>/dev/null; then
33
+ echo "" >> "$HOME/.bashrc"
34
+ echo "# ❄️ ICE v4.3 Auto-Load" >> "$HOME/.bashrc"
35
+ echo "[ -f \"$ICE_DIR/ice-auto-load.sh\" ] && source \"$ICE_DIR/ice-auto-load.sh\"" >> "$HOME/.bashrc"
36
+ echo "✅ Added auto-load to ~/.bashrc"
37
+ else
38
+ echo "ℹ️ Auto-load already in ~/.bashrc"
39
+ fi
40
+
41
+ # Create .env template if not exists
42
+ if [ ! -f "$ICE_DIR/.env" ]; then
43
+ echo "📝 Creating .env template..."
44
+ cat > "$ICE_DIR/.env" << 'ENVTEMPLATE'
45
+ # ❄️ ICE v4.3 — API Keys Configuration
46
+ # NEVER commit this file to git!
47
+
48
+ # Groq API Key (get from https://console.groq.com)
49
+ GROQ_API_KEY=
50
+
51
+ # Gemini API Key (get from https://aistudio.google.com)
52
+ GEMINI_API_KEY=
53
+
54
+ # Qwen OAuth — No key needed (built into Qwen Code)
55
+ ENVTEMPLATE
56
+ chmod 600 "$ICE_DIR/.env"
57
+ echo "⚠️ Edit $ICE_DIR/.env and add your API keys"
58
+ fi
59
+
60
+ echo ""
61
+ echo "=" | tr -d '\n' && printf '%.0s=' {1..60} && echo
62
+ echo "✅ ICE v4.3 installed successfully!"
63
+ echo ""
64
+ echo "📚 Next steps:"
65
+ echo " 1. Edit ~/.qwen/.env and add your API keys"
66
+ echo " 2. Run: source ~/.bashrc"
67
+ echo " 3. Type: ice (to test ICE CLI)"
68
+ echo ""
69
+ echo "🔗 GitHub: github.com/anh3d0nic/qwen-code-termux-ice"
70
+ echo "=" | tr -d '\n' && printf '%.0s=' {1..60} && echo