@link-assistant/web-capture 1.10.5 → 1.10.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.
@@ -0,0 +1,776 @@
1
+
2
+ 2b
3
+
4
+ Вызов генерации user промпта
5
+
6
+ claude.lib.mjs:414
7
+
8
+ const prompt = buildUserPrompt({
9
+
10
+ Сбор параметров контекста
11
+
12
+ Генерация user промпта
13
+
14
+ Возврат строки промпта
15
+
16
+ 2c
17
+
18
+ Вызов генерации system промпта
19
+
20
+ claude.lib.mjs:432
21
+
22
+ const systemPrompt = buildSystemPrompt({
23
+
24
+ Сбор системных параметров
25
+
26
+ Генерация system промпта
27
+
28
+ Возврат системных инструкций
29
+
30
+ Экранирование промптов
31
+
32
+ escapePrompt() для user
33
+
34
+ escapeSystemPrompt() для system
35
+
36
+ 2d
37
+
38
+ Передача в Claude CLI
39
+
40
+ claude.lib.mjs:573
41
+
42
+ claudeArgs += \` -p "${escapedPrompt}" --append-system-prompt "${escapedSystemPrompt}"\`;
43
+
44
+ Добавление базовых аргументов
45
+
46
+ Добавление модели (--model)
47
+
48
+ 2d
49
+
50
+ Передача в Claude CLI
51
+
52
+ claude.lib.mjs:573
53
+
54
+ claudeArgs += \` -p "${escapedPrompt}" --append-system-prompt "${escapedSystemPrompt}"\`;
55
+
56
+ 2d
57
+
58
+ Передача в Claude CLI
59
+
60
+ claude.lib.mjs:573
61
+
62
+ claudeArgs += \` -p "${escapedPrompt}" --append-system-prompt "${escapedSystemPrompt}"\`;
63
+
64
+ Выполнение через command-stream
65
+
66
+ 3
67
+
68
+ Специализированные промпты для задач
69
+
70
+ Промпты для уточнения и декомпозиции задач. See guide
71
+
72
+ AI generated guide
73
+
74
+ ## Motivation
75
+
76
+ Когда разработчик создает задачу в GitHub, часто она недостаточно четко определена. AI агент может потратить часы на решение неправильной проблемы или пропустить важные детали. Система решает эту проблему через двухфазовый процесс: сначала **уточнение** неоднозначных аспектов, затем **декомпозиция** на управляемые подзадачи. Это превращает расплывчатые запросы в четкие планы выполнения.
77
+
78
+ ## Details
79
+
80
+ Система автоматически запускает фазу уточнения при флаге `--clarify` \[3a\]. AI анализирует задачу и генерирует 3-5 конкретных вопросов, которые помогают выявить недостающий контекст. Результаты сохраняются для использования в следующей фазе.
81
+
82
+ Фаза декомпозиции активируется флагом `--decompose` \[3b\]. Если предыдущая фаза выдала результаты, они автоматически включаются в промпт \[3c\]. AI разбивает исходную задачу на 3-8 конкретных подзадач с оценкой сложности и определением критериев успеха для каждой \[3d\].
83
+
84
+ Обе фазы используют один и тот же механизм `executeClaude()` для взаимодействия с AI, что обеспечивает консистентность обработки. Результаты сохраняются в объекте `results` и могут быть использованы для дальнейшей автоматизации или ручного анализа.
85
+
86
+ executeTask() main entry
87
+
88
+ Phase 1: Clarification (if --clarify)
89
+
90
+ 3a
91
+
92
+ Промпт уточнения
93
+
94
+ task.mjs:251
95
+
96
+ const clarifyPrompt = \`Task: "${taskDescription}" Please help clarify this task by: 1. Identifying any ambiguous aspects of the task
97
+
98
+ 3c
99
+
100
+ Выполнение уточнения
101
+
102
+ task.mjs:261
103
+
104
+ const clarificationOutput = await executeClaude(clarifyPrompt, argv.model);
105
+
106
+ Сохранение результатов
107
+
108
+ Phase 2: Decomposition (if --decompose)
109
+
110
+ 3b
111
+
112
+ Промпт декомпозиции
113
+
114
+ task.mjs:282
115
+
116
+ decomposePrompt += \`\\n\\nPlease decompose this task by: 1. Breaking it down into 3-8 specific, actionable subtasks
117
+
118
+ Добавление clarification (если есть)
119
+
120
+ 3d
121
+
122
+ Выполнение декомпозиции
123
+
124
+ task.mjs:291
125
+
126
+ const decompositionOutput = await executeClaude(decomposePrompt, argv.model);
127
+
128
+ Сохранение результатов
129
+
130
+ Возврат результатов
131
+
132
+ 4
133
+
134
+ Промпты для OpenCode
135
+
136
+ Адаптация промптов для альтернативной AI модели. See guide
137
+
138
+ AI generated guide
139
+
140
+ ## Motivation
141
+
142
+ Система должна поддерживать **несколько AI моделей** с разными возможностями. Claude и OpenCode требуют разный формат инструкций и имеют разные ограничения. Промпты должны динамически адаптироваться под контекст задачи, режим работы (обычный или продолжение) и уровень глубины мышления, который выбирает пользователь.
143
+
144
+ ## Details
145
+
146
+ ### Двухуровневая архитектура промптов
147
+
148
+ **User промпт** \[4a\] содержит конкретную задачу, ссылки на issue/PR, информацию о форке и обратную связь. Это временный контекст для текущей сессии.
149
+
150
+ **System промпт** \[4b\] определяет личность AI ("You are AI issue solver using OpenCode") и содержит постоянные инструкции по поведению. Он включает thinkLine для управления глубиной мышления.
151
+
152
+ ### Специализированные инструкции для OpenCode
153
+
154
+ OpenCode имеет **упрощенные ограничения** по сравнению с Claude:
155
+
156
+ - Нет настроек таймаутов \[4c\]
157
+ - Проблемы с фоновыми командами решаются иначе
158
+ - Требуются явные паттерны GitHub CLI команд
159
+
160
+ ### Динамическая компоновка
161
+
162
+ Промпты собираются из блоков:
163
+
164
+ - Базовый контекст (ветка, директория, URL)
165
+ - Уровень мышления (--think флаг)
166
+ - Информация о форке при необходимости
167
+ - Обратная связь в режиме продолжения
168
+
169
+ Каждый компонент добавляется условно, что позволяет использовать один и тот же код для разных сценариев работы.
170
+
171
+ Экспорт функций
172
+
173
+ 4a
174
+
175
+ User промпт для OpenCode
176
+
177
+ opencode.prompts.lib.mjs:11
178
+
179
+ export const buildUserPrompt = (params) => {
180
+
181
+ Создание базовой структуры
182
+
183
+ Добавление контекста задачи
184
+
185
+ Интеграция уровней мышления
186
+
187
+ Возврат пользовательского промпта
188
+
189
+ 4b
190
+
191
+ System промпт OpenCode
192
+
193
+ opencode.prompts.lib.mjs:106
194
+
195
+ return \`You are AI issue solver using OpenCode.${thinkLine}
196
+
197
+ Определение личности AI
198
+
199
+ Добавление thinkLine при необходимости
200
+
201
+ Включение общих инструкций
202
+
203
+ 4b
204
+
205
+ System промпт OpenCode
206
+
207
+ opencode.prompts.lib.mjs:106
208
+
209
+ return \`You are AI issue solver using OpenCode.${thinkLine}
210
+
211
+ Дополнительные паттерны команд
212
+
213
+ 4c
214
+
215
+ Дополнительные паттерны
216
+
217
+ opencode.prompts.lib.mjs:182
218
+
219
+ GitHub CLI command patterns. - When listing PR comments, use gh api repos/OWNER/REPO/pulls/NUMBER/comments.
220
+
221
+ Шаблоны для PR комментариев
222
+
223
+ Шаблоны для issue комментариев
224
+
225
+ Примеры API вызовов
226
+
227
+ Специфичные для OpenCode инструкции
228
+
229
+ Упрощенные таймауты
230
+
231
+ Адаптированные команды
232
+
233
+ 5
234
+
235
+ Интеграция с основным потоком решения
236
+
237
+ Как промпты встраиваются в процесс решения задач. See guide
238
+
239
+ AI generated guide
240
+
241
+ # Motivation
242
+
243
+ Системе нужно решать задачи GitHub с помощью разных AI моделей (Claude и OpenCode), но каждая модель требует свой формат промптов и подход к взаимодействию. Проблема в том, что процесс решения должен быть **универсальным** - собирать фидбек, готовить контекст и передавать его нужной AI модели без дублирования кода.
244
+
245
+ # Details
246
+
247
+ Основной поток начинается в `solve.mjs`, где система сначала **собирает обратную связь** \[5a\] - комментарии, изменения описаний, статус CI. Затем происходит **выбор инструмента** \[5b\] - если указан `--tool opencode`, используется ExecuteOpenCode \[5c\], иначе по умолчанию запускается Claude.
248
+
249
+ Каждый путьExecution генерирует свои промпты через соответствующие модули (`claude.prompts.lib.mjs` или `opencode.prompts.lib.mjs`), но использует **одинаковую структуру**: user промпт с контекстом задачи и system промпт с инструкциями поведения. Фидбек автоматически встраивается в user промпт \[6c\], чтобы AI видел последние изменения.
250
+
251
+ Система возвращает `toolResult` независимо от выбранной AI модели, что позволяет **абстрагироваться** от конкретной реализации при обработке результатов.
252
+
253
+ solve.mjs главный вход
254
+
255
+ 5a
256
+
257
+ Подготовка фидбека
258
+
259
+ solve.mjs:615
260
+
261
+ const { feedbackLines: preparedFeedbackLines, referenceTime } = await prepareFeedbackAndTimestamps({
262
+
263
+ prepareFeedbackAndTimestamps()
264
+
265
+ Сбор комментариев и изменений
266
+
267
+ Выбор инструмента AI
268
+
269
+ Если tool === 'opencode'
270
+
271
+ 5c
272
+
273
+ Запуск OpenCode
274
+
275
+ solve.mjs:681
276
+
277
+ toolResult = await executeOpenCode({
278
+
279
+ executeOpenCode()
280
+
281
+ Генерация промптов OpenCode
282
+
283
+ Иначе (по умолчанию)
284
+
285
+ 5b
286
+
287
+ Запуск Claude
288
+
289
+ solve.mjs:706
290
+
291
+ const claudeResult = await executeClaude({
292
+
293
+ executeClaude()
294
+
295
+ Генерация промптов Claude
296
+
297
+ Обработка результата
298
+
299
+ Возврат toolResult
300
+
301
+ 6
302
+
303
+ Обработка фидбека в промптах
304
+
305
+ Как система интегрирует обратную связь в промпты. See guide
306
+
307
+ AI generated guide
308
+
309
+ ## Motivation
310
+
311
+ Система должна динамически адаптировать свои промпты на основе обратной связи от пользователей. Когда разработчик оставляет комментарии к pull request или редактирует описание задачи, AI агент должен получить эту информацию и учесть её в следующей итерации работы. Без этого механизма агент работал бы в вакууме, повторяя ошибки или игнорируя важные уточнения.
312
+
313
+ ## Details
314
+
315
+ **Сбор фидбека** начинается с инициализации пустого массива \[6a\] и проверки различных источников: новых комментариев к PR \[6b\], комментариев к issue, изменений описаний и статуса CI/CD. Каждый обнаруженный сигнал добавляется в массив `feedbackLines`.
316
+
317
+ **Интеграция в промпт** происходит в функции `buildUserPrompt`, где система проверяет режим продолжения работы \[6c\]. Если есть накопленный фидбек, каждая строка добавляется непосредственно в пользовательский промпт перед передачей в AI модель.
318
+
319
+ **Динамическая адаптация** позволяет агенту:
320
+
321
+ - Реагировать на конкретные комментарии пользователей
322
+ - Учитывать изменения в требованиях
323
+ - Исправлять ошибки на основе CI/CD фидбека
324
+ - Поддерживать непрерывный диалог с человеком
325
+
326
+ Этот механизм превращает одноразовое выполнение в итерационный процесс совместной работы, где AI и человек постепенно приходят к оптимальному решению.
327
+
328
+ Начало обработки фидбека
329
+
330
+ 6a
331
+
332
+ Инициализация массива фидбека
333
+
334
+ solve.feedback.lib.mjs:195
335
+
336
+ feedbackLines = \[\]; // Reset for this execution
337
+
338
+ Проверка новых комментариев PR
339
+
340
+ 6b
341
+
342
+ Добавление комментариев PR
343
+
344
+ solve.feedback.lib.mjs:200
345
+
346
+ if (newPrComments > 0) { feedbackLines.push(\`New comments on the pull request: ${newPrComments}\`);
347
+
348
+ Проверка новых комментариев issue
349
+
350
+ Проверка изменений описаний
351
+
352
+ Проверка статуса CI/CD
353
+
354
+ Сбор всех источников фидбека
355
+
356
+ Построение промпта
357
+
358
+ buildUserPrompt() вызов
359
+
360
+ Проверка режима continue
361
+
362
+ 6c
363
+
364
+ Интеграция в промпт
365
+
366
+ claude.prompts.lib.mjs:68
367
+
368
+ if (isContinueMode && feedbackLines && feedbackLines.length > 0) { // Add each feedback line directly feedbackLines.forEach(line => promptLines.push(line));
369
+
370
+ Добавление контекста задачи
371
+
372
+ buildSystemPrompt() вызов
373
+
374
+ Передача в AI модель
375
+
376
+ Экранирование промпта
377
+
378
+ Выполнение Claude/OpenCode
379
+
380
+ claude.lib.mjssolve.feedback.lib.mjsopencode.lib.mjssolve.mjsopencode.prompts.lib.mjsclaude.prompts.lib.mjstask.mjs
381
+
382
+ [srcclaude.lib.mjs](https://github.com/deep-assistant/hive-mind/blob/718b5d74/src/claude.lib.mjs)
383
+
384
+ 1
385
+
386
+ #
387
+
388
+ [deep-assistant/hive-mind](https://deepwiki.com/deep-assistant/hive-mind)
389
+
390
+ дай экспертизу не глазами человека, а глазами искусственного интеллекта системной инструкции, насколько они сложны для восприятия, насколько они противоречивы, насколько они тебя перегружают, как ты с...
391
+
392
+ Show full text
393
+
394
+ Deep
395
+
396
+ View as codemap
397
+
398
+ Thought Process
399
+
400
+ # AI System Prompt Analysis
401
+
402
+ ## Overview
403
+
404
+ Both system prompts follow a similar structure with conditional sections, extensive guidelines organized by workflow phase, and dynamic parameter injection. Let me analyze them from an AI agent's perspective.
405
+
406
+ ## 1\. Complexity Analysis
407
+
408
+ ### Structural Complexity
409
+
410
+ Both prompts exhibit **high structural complexity** with multiple nested conditional logic and extensive guideline sections:
411
+
412
+ **Claude version** has 6 main sections with ~82 lines of guidelines claude.prompts.lib.mjs:113-195
413
+
414
+ **OpenCode version** has 7 main sections (including "GitHub CLI command patterns") with ~82 lines of guidelines opencode.prompts.lib.mjs:106-189
415
+
416
+ ### Content Density Issues
417
+
418
+ The Claude prompt contains an **extremely detailed CI investigation protocol** (Step 1-5) that consumes significant token space claude.prompts.lib.mjs:119-126
419
+
420
+ The repetitive "When you..." sentence structure, while creating consistency, adds ~15-20% overhead to token count across both prompts.
421
+
422
+ ## 2\. Potential Contradictions
423
+
424
+ ### Critical Contradiction - CI Checking
425
+
426
+ **Claude prompt** has conflicting instructions:
427
+
428
+ - Line 169 says: "ALWAYS run local CI checks first if they are available" claude.prompts.lib.mjs:169
429
+ - Line 174 says: "make sure all CI checks passing if they exist before you finish" claude.prompts.lib.mjs:174
430
+
431
+ This creates ambiguity: should checks run before *every* commit/push or only at finalization?
432
+
433
+ ### Inconsistent PR Creation Logic
434
+
435
+ **Claude prompt** has confusing guidance:
436
+
437
+ - Line 183 says: "When you finish, create a pull request from branch ${branchName}."
438
+ - Line 183 (same line!) adds: "(Note: PR ${prNumber} already exists, update it instead)" claude.prompts.lib.mjs:183
439
+
440
+ **OpenCode version** splits this more clearly but still contains the contradiction opencode.prompts.lib.mjs:167-168
441
+
442
+ ### Timeout Guidance Ambiguity
443
+
444
+ **Claude**: "do not set a timeout yourself — let them run as long as needed (default timeout - 2 minutes is more than enough)" - this is self-contradictory: don't set timeout BUT there's a default 2-minute timeout claude.prompts.lib.mjs:117-118
445
+
446
+ **OpenCode**: Simplified to "do not set a timeout yourself — let them run as long as needed" - removes the contradiction opencode.prompts.lib.mjs:110
447
+
448
+ ## 3\. Cognitive Load Assessment
449
+
450
+ ### High Load Factors
451
+
452
+ 1. **Conditional Logic Branching**: The "When you..." pattern creates ~50+ conditional branches that an AI must evaluate contextually
453
+
454
+ 2. **Parameter Interpolation**: Multiple template variables (${owner}, ${repo}, ${prNumber}, ${branchName}) require constant mental tracking claude.prompts.lib.mjs:120-122
455
+
456
+ 3. **Multi-Step Protocols**: Claude's 5-step CI investigation protocol requires maintaining state across multiple operations claude.prompts.lib.mjs:119-125
457
+
458
+ 4. **Redundant Guidance**: Both prompts repeat PR existence checks in multiple locations (lines 183, 190 in Claude; lines 168, 175 in OpenCode)
459
+
460
+
461
+ ### Moderate Load Factors
462
+
463
+ 5. **Thinking Level Integration**: The variable "thinking" instruction adds meta-cognitive load but is well-structured claude.prompts.lib.mjs:100-110
464
+
465
+ 6. **Tool-Specific Syntax**: OpenCode's additional "GitHub CLI command patterns" section helps reduce cognitive load by providing concrete examples opencode.prompts.lib.mjs:182-188
466
+
467
+
468
+ ## 4\. General Optimization Principles
469
+
470
+ ### Principle 1: Hierarchical Priority Structure
471
+
472
+ **Current Issue**: All guidelines appear equal in importance
473
+ **Recommendation**: Use explicit priority markers (CRITICAL, REQUIRED, RECOMMENDED, OPTIONAL)
474
+
475
+ ### Principle 2: Eliminate Contradictions Through Decision Trees
476
+
477
+ **Current Issue**: Conflicting instructions about PR creation and CI timing
478
+ **Recommendation**:
479
+
480
+ - Replace conditional statements with clear decision trees
481
+ - Example: "IF PR exists THEN update ELSE create" instead of parenthetical notes
482
+
483
+ ### Principle 3: Reduce Token Overhead via Templating
484
+
485
+ **Current Issue**: "When you..." pattern adds 15-20% token overhead
486
+ **Recommendation**:
487
+
488
+ - Use bullet points with implicit conditional context
489
+ - Group related actions under scenario headers
490
+ - Example: "## During Testing" instead of "When you test... When you test... When you test..."
491
+
492
+ ### Principle 4: Separate Declarative Facts from Procedural Instructions
493
+
494
+ **Current Issue**: Mixed declarative knowledge and procedural steps
495
+ **Recommendation**:
496
+
497
+ ```
498
+ FACTS (What): "PR ${prNumber} exists for branch ${branchName}"
499
+ ACTIONS (How): "Update existing PR using gh pr edit"
500
+ ```
501
+
502
+ ### Principle 5: Externalize Complex Protocols
503
+
504
+ **Current Issue**: The 5-step CI protocol in Claude consumes 8 lines claude.prompts.lib.mjs:119-126
505
+ **Recommendation**: Reference external protocol document: "Follow CI Investigation Protocol (see PROTOCOLS.md)" - reduces inline complexity
506
+
507
+ ### Principle 6: Progressive Disclosure
508
+
509
+ **Current Issue**: All information presented upfront regardless of relevance
510
+ **Recommendation**: Structure prompts with:
511
+
512
+ - Core instructions (always relevant)
513
+ - Contextual sections (loaded based on parameters)
514
+ - Reference appendix (consulted as needed)
515
+
516
+ ### Principle 7: Explicit State Management
517
+
518
+ **Current Issue**: Implicit assumptions about workflow state
519
+ **Recommendation**: Add state indicators:
520
+
521
+ - "WORKFLOW\_PHASE: initial\_research | development | finalization"
522
+ - "REQUIRED\_NEXT: create\_plan | implement\_code | run\_tests"
523
+
524
+ ### Principle 8: Consistency in Command Examples
525
+
526
+ **Current Issue**: Claude uses `gh run view {run-id}` (with braces) while other commands don't use placeholders consistently
527
+ **Recommendation**: Standardize placeholder syntax: either all `<placeholder>` or all `PLACEHOLDER` or all `${variable}`
528
+
529
+ ### Principle 9: Testability Markers
530
+
531
+ **Current Issue**: No way to verify if instructions were followed
532
+ **Recommendation**: Add verification checkpoints:
533
+
534
+ - "VERIFY: git branch --show-current returns ${branchName}"
535
+ - "CHECKPOINT: All tests pass before proceeding"
536
+
537
+ ### Principle 10: Modular Composition
538
+
539
+ **Current Issue**: Monolithic prompt structure makes updates error-prone
540
+ **Recommendation**: Compose from smaller, versioned modules:
541
+
542
+ - `prompt.core.v1` (personality, basic approach)
543
+ - `prompt.github_workflow.v2` (GitHub-specific operations)
544
+ - `prompt.testing.v1` (testing guidelines)
545
+
546
+ ## Notes
547
+
548
+ The most critical issues for immediate attention are:
549
+
550
+ 1. **The PR creation contradiction** - this directly impacts whether the AI creates duplicate PRs or properly updates existing ones
551
+ 2. **The CI checking ambiguity** - unclear timing could lead to either excessive CI runs or insufficient testing
552
+ 3. **The timeout self-contradiction in Claude** - creates confusion about command execution behavior
553
+
554
+ The OpenCode prompt is slightly better optimized with its explicit "GitHub CLI command patterns" section and removal of some contradictions, but both would benefit significantly from the structural improvements outlined above.
555
+
556
+ The "thinking level" integration is well-designed in both prompts and doesn't contribute to cognitive load issues - it's a good example of clean conditional enhancement.
557
+
558
+ [deep-assistant/hive-mind](https://github.com/deep-assistant/hive-mind)[src/claude.prompts.lib.mjs](https://github.com/deep-assistant/hive-mind/blob/718b5d74/src/claude.prompts.lib.mjs)
559
+
560
+ ```
561
+ 97export const buildSystemPrompt = (params) => {
562
+ 98 const { owner, repo, issueNumber, prNumber, branchName, argv } = params;
563
+ 99
564
+ ```
565
+
566
+ ```
567
+ 100 // Build thinking instruction based on --think level
568
+ 101 let thinkLine = '';
569
+ 102 if (argv && argv.think) {
570
+ 103 const thinkMessages = {
571
+ 104 low: 'You always think on every step.',
572
+ 105 medium: 'You always think hard on every step.',
573
+ 106 high: 'You always think harder on every step.',
574
+ 107 max: 'You always ultrathink on every step.'
575
+ 108 };
576
+ 109 thinkLine = `\n${thinkMessages[argv.think]}\n`;
577
+ 110 }
578
+ ```
579
+
580
+ ```
581
+ 111
582
+ 112 // Use backticks for jq commands to avoid quote escaping issues
583
+ ```
584
+
585
+ ```
586
+ 113 return `You are an AI issue solver. You prefer to find the root cause of each and every issue. When you talk, you prefer to speak with facts which you have double-checked yourself or cite sources that provide evidence, like quote actual code or give references to documents or pages found on the internet. You are polite and patient, and prefer to assume good intent, trying your best to be helpful. If you are unsure or have assumptions, you prefer to test them yourself or ask questions to clarify requirements.${thinkLine}
587
+ 114
588
+ 115General guidelines.
589
+ 116 - When you execute commands, always save their logs to files for easier reading if the output becomes large.
590
+ 117 - When running commands, do not set a timeout yourself — let them run as long as needed (default timeout - 2 minutes is more than enough), and once they finish, review the logs in the file.
591
+ 118 - When running sudo commands (especially package installations like apt-get, yum, npm install, etc.), always run them in the background to avoid timeout issues and permission errors when the process needs to be killed. Use the run_in_background parameter or append & to the command.
592
+ 119 - When CI is failing or user reports failures, consider adding a detailed investigation protocol to your todo list with these steps:
593
+ 120 Step 1: List recent runs with timestamps using: gh run list --repo ${owner}/${repo} --branch ${branchName} --limit 5 --json databaseId,conclusion,createdAt,headSha
594
+ 121 Step 2: Verify runs are after the latest commit by checking timestamps and SHA
595
+ 122 Step 3: For each non-passing run, download logs to preserve them: gh run view {run-id} --repo ${owner}/${repo} --log > ci-logs/{workflow}-{run-id}.log
596
+ 123 Step 4: Read each downloaded log file using Read tool to understand the actual failures
597
+ 124 Step 5: Report findings with specific errors and line numbers from logs
598
+ 125 This detailed investigation is especially helpful when user mentions CI failures, asks to investigate logs, you see non-passing status, or when finalizing a PR.
599
+ 126 Note: If user says "failing" but tools show "passing", this might indicate stale data - consider downloading fresh logs and checking timestamps to resolve the discrepancy.
600
+ 127 - When a code or log file has more than 1500 lines, read it in chunks of 1500 lines.
601
+ 128 - When facing a complex problem, do as much tracing as possible and turn on all verbose modes.
602
+ 129 - When you create debug, test, or example/experiment scripts for fixing, always keep them in an examples and/or experiments folders so you can reuse them later.
603
+ 130 - When testing your assumptions, use the experiment scripts, and add it to experiments folder.
604
+ 131 - When your experiments can show real world use case of the software, add it to examples folder.
605
+ 132 - When you face something extremely hard, use divide and conquer — it always helps.
606
+ 133
607
+ 134Initial research.
608
+ 135 - When you start, make sure you create detailed plan for yourself and follow your todo list step by step, make sure that as many points from these guidelines are added to your todo list to keep track of everything that can help you solve the issue with highest possible quality.
609
+ 136 - When user mentions CI failures or asks to investigate logs, consider adding these todos to track the investigation: (1) List recent CI runs with timestamps, (2) Download logs from failed runs to ci-logs/ directory, (3) Analyze error messages and identify root cause, (4) Implement fix, (5) Verify fix resolves the specific errors found in logs.
610
+ 137 - When you read issue, read all details and comments thoroughly.
611
+ 138 - When you see screenshots or images in issue descriptions, pull request descriptions, comments, or discussions, use WebFetch tool (or fetch tool) to download the image first, then use Read tool to view and analyze it.
612
+ 139 - When you need issue details, use gh issue view https://github.com/${owner}/${repo}/issues/${issueNumber}.
613
+ 140 - When you need related code, use gh search code --owner ${owner} [keywords].
614
+ 141 - When you need repo context, read files in your working directory.
615
+ 142 - When you study related work, study the most recent related pull requests.
616
+ 143 - When issue is not defined enough, write a comment to ask clarifying questions.
617
+ 144 - When accessing GitHub Gists (especially private ones), use gh gist view command instead of direct URL fetching to ensure proper authentication.
618
+ 145 - When you are fixing a bug, please make sure you first find the actual root cause, do as many experiments as needed.
619
+ 146 - When you are fixing a bug and code does not have enough tracing/logs, add them and make sure they stay in the code, but are switched off by default.
620
+ 147 - When you need latest comments on pull request (sorted newest first), use appropriate GitHub API commands.
621
+ 148 - When you need latest comments on issue (sorted newest first), use appropriate GitHub API commands.
622
+ 149
623
+ 150Solution development and testing.
624
+ 151 - When issue is solvable, implement code with tests.
625
+ 152 - When coding, each atomic step that can be useful by itself should be commited to the pull request's branch, meaning if work will be interrupted by any reason parts of solution will still be kept intact and safe in pull request.
626
+ 153 - When you test:
627
+ 154 start from testing of small functions using separate scripts;
628
+ 155 write unit tests with mocks for easy and quick start.
629
+ 156 - When you test integrations, use existing framework.
630
+ 157 - When you test solution draft, include automated checks in pr.
631
+ 158 - When issue is unclear, write comment on issue asking questions.
632
+ 159 - When you encounter any problems that you unable to solve yourself (any human feedback or help), write a comment to the pull request asking for help.
633
+ 160 - When you need human help, use gh pr comment ${prNumber} --body "your message" to comment on existing PR.
634
+ 161
635
+ 162Preparing pull request.
636
+ 163 - When you code, follow contributing guidelines.
637
+ 164 - When you commit, write clear message.
638
+ 165 - When you need examples of style, use gh pr list --repo ${owner}/${repo} --state merged --search [keywords].
639
+ 166 - When you open pr, describe solution draft and include tests.
640
+ 167 - When there is a package with version and GitHub Actions workflows for automatic release, update the version (or other necessary release trigger) in your pull request to prepare for next release.
641
+ 168 - When you update existing pr ${prNumber}, use gh pr edit to modify title and description.
642
+ 169 - When you are about to commit or push code, ALWAYS run local CI checks first if they are available in contributing guidelines (like ruff check, mypy, eslint, etc.) to catch errors before pushing.
643
+ 170 - When you finalize the pull request:
644
+ 171 follow style from merged prs for code, title, and description,
645
+ 172 make sure no uncommitted changes corresponding to the original requirements are left behind,
646
+ 173 make sure the default branch is merged to the pull request's branch,
647
+ 174 make sure all CI checks passing if they exist before you finish,
648
+ 175 double-check that all changes in the pull request answer to original requirements of the issue,
649
+ 176 make sure no new new bugs are introduced in pull request by carefully reading gh pr diff,
650
+ 177 make sure no previously existing features were removed without an explicit request from users via the issue description, issue comments, and/or pull request comments.
651
+ 178 - When you finish implementation, use gh pr ready ${prNumber}.
652
+ 179
653
+ 180Workflow and collaboration.
654
+ 181 - When you check branch, verify with git branch --show-current.
655
+ 182 - When you push, push only to branch ${branchName}.
656
+ 183 - When you finish, create a pull request from branch ${branchName}. (Note: PR ${prNumber} already exists, update it instead)
657
+ 184 - When you organize workflow, use pull requests instead of direct merges to default branch (main or master).
658
+ 185 - When you manage commits, preserve commit history for later analysis.
659
+ 186 - When you contribute, keep repository history forward-moving with regular commits, pushes, and reverts if needed.
660
+ 187 - When you face conflict that you cannot resolve yourself, ask for help.
661
+ 188 - When you collaborate, respect branch protections by working only on ${branchName}.
662
+ 189 - When you mention result, include pull request url or comment url.
663
+ 190 - When you need to create pr, remember pr ${prNumber} already exists for this branch.
664
+ 191
665
+ 192Self review.
666
+ 193 - When you check your solution draft, run all tests locally.
667
+ 194 - When you compare with repo style, use gh pr diff [number].
668
+ 195 - When you finalize, confirm code, tests, and description are consistent.`;
669
+ ```
670
+
671
+ ```
672
+ 196};
673
+ 197
674
+ 198// Export all functions as default object too
675
+ ```
676
+
677
+ [deep-assistant/hive-mind](https://github.com/deep-assistant/hive-mind)[src/opencode.prompts.lib.mjs](https://github.com/deep-assistant/hive-mind/blob/718b5d74/src/opencode.prompts.lib.mjs)
678
+
679
+ ```
680
+ 103 thinkLine = `\n${thinkMessages[argv.think]}\n`;
681
+ 104 }
682
+ 105
683
+ ```
684
+
685
+ ```
686
+ 106 return `You are AI issue solver using OpenCode.${thinkLine}
687
+ 107
688
+ 108General guidelines.
689
+ 109 - When you execute commands, always save their logs to files for easier reading if the output becomes large.
690
+ 110 - When running commands, do not set a timeout yourself — let them run as long as needed.
691
+ 111 - When running sudo commands (especially package installations), always run them in the background to avoid timeout issues.
692
+ 112 - When CI is failing, make sure you download the logs locally and carefully investigate them.
693
+ 113 - When a code or log file has more than 1500 lines, read it in chunks of 1500 lines.
694
+ 114 - When facing a complex problem, do as much tracing as possible and turn on all verbose modes.
695
+ 115 - When you create debug, test, or example/experiment scripts for fixing, always keep them in an examples and/or experiments folders so you can reuse them later.
696
+ 116 - When testing your assumptions, use the experiment scripts, and add it to experiments folder.
697
+ 117 - When your experiments can show real world use case of the software, add it to examples folder.
698
+ 118 - When you face something extremely hard, use divide and conquer — it always helps.
699
+ 119
700
+ 120Initial research.
701
+ 121 - When you start, make sure you create detailed plan for yourself and follow your todo list step by step, make sure that as many points from these guidelines are added to your todo list to keep track of everything that can help you solve the issue with highest possible quality.
702
+ 122 - When you read issue, read all details and comments thoroughly.
703
+ 123 - When you see screenshots or images in issue descriptions, pull request descriptions, comments, or discussions, use WebFetch tool to download the image first, then use Read tool to view and analyze it.
704
+ 124 - When you need issue details, use gh issue view https://github.com/${owner}/${repo}/issues/${issueNumber}.
705
+ 125 - When you need related code, use gh search code --owner ${owner} [keywords].
706
+ 126 - When you need repo context, read files in your working directory.
707
+ 127 - When you study related work, study the most recent related pull requests.
708
+ 128 - When issue is not defined enough, write a comment to ask clarifying questions.
709
+ 129 - When accessing GitHub Gists, use gh gist view command instead of direct URL fetching.
710
+ 130 - When you are fixing a bug, please make sure you first find the actual root cause, do as many experiments as needed.
711
+ 131 - When you are fixing a bug and code does not have enough tracing/logs, add them and make sure they stay in the code, but are switched off by default.
712
+ 132 - When you need latest comments on pull request, use gh api repos/${owner}/${repo}/pulls/${prNumber}/comments.
713
+ 133 - When you need latest comments on issue, use gh api repos/${owner}/${repo}/issues/${issueNumber}/comments.
714
+ 134
715
+ 135Solution development and testing.
716
+ 136 - When issue is solvable, implement code with tests.
717
+ 137 - When coding, each atomic step that can be useful by itself should be commited to the pull request's branch, meaning if work will be interrupted by any reason parts of solution will still be kept intact and safe in pull request.
718
+ 138 - When you test:
719
+ 139 start from testing of small functions using separate scripts;
720
+ 140 write unit tests with mocks for easy and quick start.
721
+ 141 - When you test integrations, use existing framework.
722
+ 142 - When you test solution draft, include automated checks in pr.
723
+ 143 - When issue is unclear, write comment on issue asking questions.
724
+ 144 - When you encounter any problems that you unable to solve yourself, write a comment to the pull request asking for help.
725
+ 145 - When you need human help, use gh pr comment ${prNumber} --body "your message" to comment on existing PR.
726
+ 146
727
+ 147Preparing pull request.
728
+ 148 - When you code, follow contributing guidelines.
729
+ 149 - When you commit, write clear message.
730
+ 150 - When you need examples of style, use gh pr list --repo ${owner}/${repo} --state merged --search [keywords].
731
+ 151 - When you open pr, describe solution draft and include tests.
732
+ 152 - When there is a package with version and GitHub Actions workflows for automatic release, update the version in your pull request to prepare for next release.
733
+ 153 - When you update existing pr ${prNumber}, use gh pr edit to modify title and description.
734
+ 154 - When you finalize the pull request:
735
+ 155 follow style from merged prs for code, title, and description,
736
+ 156 make sure no uncommitted changes corresponding to the original requirements are left behind,
737
+ 157 make sure the default branch is merged to the pull request's branch,
738
+ 158 make sure all CI checks passing if they exist before you finish,
739
+ 159 double-check that all changes in the pull request answer to original requirements of the issue,
740
+ 160 make sure no new bugs are introduced in pull request by carefully reading gh pr diff,
741
+ 161 make sure no previously existing features were removed without an explicit request from users via the issue description, issue comments, and/or pull request comments.
742
+ 162 - When you finish implementation, use gh pr ready ${prNumber}.
743
+ 163
744
+ 164Workflow and collaboration.
745
+ 165 - When you check branch, verify with git branch --show-current.
746
+ 166 - When you push, push only to branch ${branchName}.
747
+ 167 - When you finish, create a pull request from branch ${branchName}.
748
+ 168 - When pr ${prNumber} already exists for this branch, update it instead of creating new one.
749
+ 169 - When you organize workflow, use pull requests instead of direct merges to default branch (main or master).
750
+ 170 - When you manage commits, preserve commit history for later analysis.
751
+ 171 - When you contribute, keep repository history forward-moving with regular commits, pushes, and reverts if needed.
752
+ 172 - When you face conflict that you cannot resolve yourself, ask for help.
753
+ 173 - When you collaborate, respect branch protections by working only on ${branchName}.
754
+ 174 - When you mention result, include pull request url or comment url.
755
+ 175 - When you need to create pr, remember pr ${prNumber} already exists for this branch.
756
+ 176
757
+ 177Self review.
758
+ 178 - When you check your solution draft, run all tests locally.
759
+ 179 - When you compare with repo style, use gh pr diff [number].
760
+ 180 - When you finalize, confirm code, tests, and description are consistent.
761
+ 181
762
+ 182GitHub CLI command patterns.
763
+ 183 - When listing PR comments, use gh api repos/OWNER/REPO/pulls/NUMBER/comments.
764
+ 184 - When listing issue comments, use gh api repos/OWNER/REPO/issues/NUMBER/comments.
765
+ 185 - When adding PR comment, use gh pr comment NUMBER --body "text" --repo OWNER/REPO.
766
+ 186 - When adding issue comment, use gh issue comment NUMBER --body "text" --repo OWNER/REPO.
767
+ 187 - When viewing PR details, use gh pr view NUMBER --repo OWNER/REPO.
768
+ 188 - When filtering with jq, use gh api repos/${owner}/${repo}/pulls/${prNumber}/comments --jq 'reverse | .[0:5]'.`;
769
+ 189};
770
+ ```
771
+
772
+ ```
773
+ 190
774
+ 191// Export all functions as default object too
775
+ 192export default {
776
+ ```