SLOPSHOPPER

ilerleme-cubugu

Süren geliştirme işinin ilerlemesini (Claude'un görev listesi ya da PLAN.md / STATE.md planı ve PROGRESS.md kaydı) prompt kutusunun üstünde çubuk olarak…

bandguardcommandtoastprompttimer
A shopper browsing a rack in a slop shop
Preview · a replayed session in a sandbox
claude · ~/work/app · ilerleme-cubugu
› fix the failing auth test and add an audit log call ⏺ Read(src/auth.ts) ⎿ Read 6 lines ⏺ Update(src/auth.ts) ⎿ Added 2 lines, removed 1 line ⏺ Bash(bun test) ⎿ 3 pass, 1 fail ● Done. refresh now rejects expired claims and logs an audit event. ✻ Worked for 42s · done 4:20 PM › /ilerleme ⎿ ilerleme-cubugu: Kullanım: /ilerleme gizle | göster | detay ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── › ? for shortcuts
README

Claude Code Araçları

Kendi işimde her gün kullandığım Claude Code modları. Kod yazmadan, Claude'a anlatarak yaptırdım; burada herkes için paylaşıyorum.

🎥 Videoda nasıl çalıştıklarını gösterdim: https://youtu.be/-B0hXhOzuUI 🏫 Soru, destek ve yeni araçlar için ücretsiz Skool topluluğu: https://www.skool.com/mustafa-dikmen-ile-yapay-zeka-1691/about

ModNe yapar
otomatik-devirOrkestra modu: /otomatik-devir:devir-otonom <görev> yazdığınız sohbet ana sohbet olur; iş, bağlamı dolunca devam notu yazan iç içe alt sohbetlere tıklamasız ve sırayla bölünür, zincir bitince ana sohbet bir özet yazar. Normal sohbetler devredilmez.
ilerleme-cubuguSüren işin ilerlemesini yazı kutusunun üstünde çubuk olarak gösterir: kaç adımın bittiği, yüzde kaç olduğu ve şu an hangi adımda olunduğu.

"Mod", Claude Code'un içine takılan küçük bir eklentidir. Claude Code'un görünüşünü ve davranışını değiştirir.

Kurulum

Gerekli: Claude Code 2.1.287 veya üstü. Terminalde claude --version yazıp bakın; eskiyse claude update.

Yol 1: Claude'a kurdurun (en kolayı)

Claude Code'u açın ve şu metni olduğu gibi yapıştırın. Komut çalıştırma izni isteyecek, onaylayın.

Şu 3 komutu sırayla çalıştır, başka hiçbir şey kurma veya değiştirme: (1) claude plugin marketplace add muctebadikmen/claude-code-araclari (2) claude plugin install otomatik-devir@muctebadikmen --scope user (3) claude plugin install ilerleme-cubugu@muctebadikmen --scope user. Sonunda claude plugin list çalıştır ve 2 modun da "enabled" olduğunu söyle. Hata olursa dur ve bana hatayı anlat.

Yol 2: Terminalden

claude plugin marketplace add muctebadikmen/claude-code-araclari
claude plugin install otomatik-devir@muctebadikmen --scope user
claude plugin install ilerleme-cubugu@muctebadikmen --scope user
claude plugin list

--scope user "tüm projelerimde geçerli olsun" demektir. Listede ikisini de "enabled" görmelisiniz. Sonra Claude Code'da yeni bir sohbet açın ya da /reload-plugins yazın.

İsterseniz yalnız birini kurabilirsiniz; iki mod birbirinden bağımsız çalışır.

Skill'ler: my-skills

Her gün kullandığım iş akışı skill'leri. Ana sohbet işi yönetir, alt ajanlar işi yapar; durum .workflow/ klasöründe tutulur, böylece iş yeni bir sohbette kaldığı yerden sürer.

SkillNe yapar
my-skill-orchestrateDiğer tüm skill'lerin uyduğu kurallar: işi alt ajanlara dağıtır, .workflow/STATE.md'yi güncel tutar
my-skill-initProjeyi başlatır: STATE.md, AGENTS.md kuralları, .gitignore
my-skill-auditKoddaki gerçek sorunları bulur ve önem sırasına dizer
my-skill-researchKodu ve web'i araştırıp tek bir öneri çıkarır
my-skill-masterplanDoğrulanmış, paralel adımlara bölünmüş plan yazar
my-skill-executePlanı alt ajanlarla uygular, her işi geri dönüşte kontrol eder
my-skill-handoffİlerlemeyi dondurur, yeni sohbet için devam prompt'u yazar
my-skill-shipGizli bilgi taraması, doğrulama, commit ve push

Akışlar: Hata için audit → masterplan → execute → ship. Yeni özellik için research → masterplan → execute → ship. handoff her an kullanılabilir.

Kurmak için:

claude plugin marketplace add muctebadikmen/claude-code-araclari
claude plugin install my-skills@muctebadikmen --scope user

Kullanmak için Claude'a doğrudan yazın: "projeyi başlat", "bu projeyi denetle", "şunu araştır", "bunun planını yap" gibi. Ya da /my-skills:my-skill-audit şeklinde çağırın.

Güncelleme

Modları geliştirdikçe buraya yüklüyorum. Yeni sürümü almak için:

claude plugin marketplace update muctebadikmen
claude plugin update otomatik-devir@muctebadikmen
claude plugin update ilerleme-cubugu@muctebadikmen
claude plugin update my-skills@muctebadikmen

Sonra Claude Code'u yeniden başlatın.

Nasıl kullanılır

otomatik-devir

Sürüm 1.1.0. Otomatik devir artık yalnızca orkestra alt sohbetlerinde çalışır. Normal bir sohbet hiç devredilmez ve Devir: durum satırı göstermez; orada /devir yazarsanız tek satırla burada devir olmadığını söyler. Alt sohbet eşikte devir dosyasını yazar, sıradaki alt sohbeti ana sohbet açar. Devir tıklamasızdır: tek bir kurulum yolu, seçilecek bir mod yok.

Devir sırasında alt ajanları bekleyen tur sonu koruması. Alt sohbette eşik aşılıp devir başladıktan sonra Claude, alt ajanlar ve Workflow'lar çalışırken turu bitirmez; her seferinde en fazla 5 dakikalık beklemelerle bekler ve sonra turu bitirmeyi yeniden dener. Devir yokken ve "Devir hazır" durumunda (dosya yazılmış) çalışan alt ajanlar ve Workflow'lar turun bitmesini engellemez. Arka plan Bash, Monitor ve geliştirme sunucuları hiç beklenmez. Esc bu beklemeyi her zaman durdurur.

Bir alt sohbette devir başlamamışken sistem prompt'una bir bölüm ekler: Claude bağlam büyüdü diye kendi başına devir yapmaz (my-skill-orchestrate/execute'un "uzun sohbet" devri dahil); devri eşikte mod yapar. Alt sohbette modelin kendi başına my-skill-handoff çağırması engellenir. Yeni sohbet açmayı da mod yasaklar: sıradakini ana sohbet açar.

Eşiğe gelince (alt sohbette):

  1. Mod Claude'a turun içinde tek bir talimat verir: elindeki adımı bitir, yeni iş başlatma, devir dosyasını yazdır (my-skill-handoff auto; beceri yoksa modun kendi devir talimatı). Dosyanın başına Kalan: var ya da Kalan: yok satırı konur.
  2. Çalışan alt ajanlar bitene kadar sistem yeni alt ajan, Workflow, Task ya da alt ajana mesaj başlatmayı koda bağlı olarak reddeder (bu yalnızca talimat değil, araç çağrısı reddedilir). Durum satırında Devir: N alt ajan bitiyor görünür.
  3. 30 dakika içinde bitmeyen işleri Claude TaskStop ile durdurur ve devir dosyasında "Yeniden çalıştır" başlığı altında listeler.
  4. Devir dosyası .workflow/handoff/<oturum-kimliği>.md yoluna yazılır. Her sohbetin kendi dosyası olduğu için aynı klasördeki sohbetler birbirinin dosyasını ezmez. Yeni alt sohbete yalnızca bu dosyayı okuması söylenir; eski .workflow/HANDOFF.md ya da STATE.md dosyalarına yönlendirilmez.
  5. Alt sohbet dosyayı yazıp turu bitirir; durum satırında Devir hazır görünür. Sıradaki alt sohbeti ana sohbet açar.

Orkestra modu (v1.1). /otomatik-devir:devir-otonom <görev> yazın; o sohbet ana sohbet olur. Ana sohbet işin kendisini yapmaz: iç içe alt sohbetleri <görev> · 1, · 2 adlarıyla tıklamasız açar ve her birini bekler. Her alt sohbet eşikte devir dosyasını yazar, ana sohbet sıradakini o dosyadan açar. Zincir şu durumlarda durur ve ana sohbet bir özet yazar: Kalan: yok, biten bir alt sohbet, yanıt vermeyi bırakan bir alt sohbet, /devir otonom dur ya da sınır. Sınır varsayılan 100 alt sohbettir; /devir otonom limit <n> ile değişir (1-1000), yalnızca bu zincir için geçerlidir ve zincir sürerken de ayarlanabilir. Esc, çökme ya da yeniden başlatma olursa şeritte Orkestra duraklatıldı: devam etmek için bir mesaj yaz. çıkar; sonraki mesajınız zinciri sürdürür. Her alt sohbet kendi çok adımlı işini my-skill-orchestrate becerisiyle alt ajanlara dağıtır (model seçimi o becerideki yönlendirmeye göre, varsayılan sonnet). Ana sohbette (ya da /otomatik-devir:devir-otonom yazmadan önce o sohbette) yazılan /devir dene alt sohbetlere uygulanır. /devir ac gerekmez: /otomatik-devir:devir-otonom <görev> yazmak yeter. Eşik, sınır ve /devir kapat ana sohbette ya da bir alt sohbette yazılınca yalnızca o zinciri etkiler; başka zincirleri ve normal sohbetleri etkilemez. /devir kapat bu zinciri durdurur: ana sohbet özet yazar, yeni alt sohbet açılmaz, süren alt sohbet devri iptal edilir. Komut listesinde kısa /devir-otonom adı görünmez; /devir ise sohbetin ilk mesajından sonra çıkar (hemen gerekirse önce herhangi bir mesaj yazın).

Mevcut kurulumunuzda eski sürümden kalan otomatik-devir-* zamanlanmış görevleri varsa mod bunları ilk yüklemede bir kez siler (görevlerin çalıştırma sohbetleri arşivlenir; arşivden geri alınabilir) ve eski kayıt anahtarlarını temizler.

KomutNe yapar
/devirDurumu gösterir; normal sohbette tek satırla burada devir olmadığını söyler
/otomatik-devir:devir-otonom <görev>Otonom zinciri başlatır; bu sohbet ana sohbet olur
/devir otonomOrkestra durumunu ve sınırı gösterir
/devir otonom durZinciri şu anki alt sohbetten sonra durdurur
/devir otonom limit <n>Bu zincirin alt sohbet sınırını ayarlar (1-1000, varsayılan 100)
/devir esik 70Bu zincirin alt sohbet eşiğini %70 yapar, ana ya da alt sohbette (1-99, varsayılan 60); başka zincirleri ve sohbetleri etkilemez; normal sohbette hiçbir şey değiştirmez
/devir dene 20Bu sohbetin deneme eşiği; alt sohbette onun, ana sohbette ya da başlatmadan önce yazılınca zincirin alt sohbetlerinin; /devir dene yazınca kaldırır
/devir simdiAlt sohbette devri hemen başlatır; normal sohbette devir yoktur
/devir kapat / /devir acAcil durdurma: yazıldığı zinciri durdurur ve süren alt sohbet devrini iptal eder; başka zincirleri ve sohbetleri etkilemez; normal sohbette hiçbir şey değiştirmez. Yazılmış devir dosyası yerinde kalır. /devir ac hiçbir şey yazmaz, kapatılan ya da biten zinciri sürdürmez: yeni zincir /otomatik-devir:devir-otonom <görev> ile başlar.

v0.x'teki mod ve geçiş komutları v1.0'da kaldırıldı. Eski komutları yazarsanız mod bunu söyleyen bir yanıt verir. Zinciri durdurmak için /devir kapat.

Kendi devir becerisi (my-skill-handoff) olanlarda mod onu kullanır. Olmayanlarda kendi hazır devir talimatını gönderir; ekstra bir şey kurmanız gerekmez.

ilerleme-cubugu

İki kaynaktan çubuk çizer:

  1. Claude'un görev listesi. Claude bir işi adımlara bölüp görev listesi tuttuğunda çubuk kendiliğinden çıkar.
  2. Plan dosyası. PLAN.md, .workflow/PLAN.md, .workflow/STATE.md ya da .workflow/plans/<klasör>/PLAN.md. Kutucuklar (- [x], - [ ]), numaralı adımlar ve - id: T1 biçimli planlar okunur. Plan dosyasının çubuğu o dosyalardan bahseden sohbete bağlanır: mesajınızda PLAN.md ya da STATE.md geçtiğinde ya da Claude bu dosyaları okuyup yazdığında çubuk çıkar. Aynı projede açtığınız alakasız bir sohbette eski plan görünmez.
  3. İlerleme kaydı. Planın klasöründe .workflow/plans/<klasör>/PROGRESS.md varsa adımların durumu oradan okunur: [ ] bekliyor, [~] sürüyor, [x] bitti, [!] engelli, [-] iptal (toplama katılmaz). Kayıt yoksa durum STATE.md'den okunur; oradan da okunamazsa çubukta ⚠ ilerleme kaydı okunamadı uyarısı çıkar.

Videodaki gibi başlatmak için örnek mesaj:

.workflow/PLAN.md ve .workflow/STATE.md: benim için bu formatta bir plan yap ve bu planı uygula. <işin tarifi>

Çubuk tek adım sürüyorsa Şu an: <adım>, birden fazla adım aynı anda sürüyorsa Şu an N iş üzerinde çalışılıyor, hiçbiri sürmüyorsa Sıradaki: <adım> yazar.

Çubuğa tıklarsanız adım listesi açılır: ✓ biten, ● süren, ○ bekleyen.

KomutNe yapar
/ilerleme detayAdım listesini açar / kapatır (çubuğa tıklamak da aynı işi yapar)
/ilerleme gizleÇubuğu gizler
/ilerleme gosterÇubuğu geri getirir

İki mod birlikte çalışır: devirden sonra yeni sohbete yapıştırılan devam prompt'u plan ya da devir dosyalarından (PLAN.md, STATE.md, HANDOFF.md) bahsettiğinde çubuk yeni sohbette de geri gelir. Bahsetmiyorsa Claude o dosyaları okuduğu anda gelir.

Kaldırma

claude plugin uninstall otomatik-devir@muctebadikmen --scope user
claude plugin uninstall ilerleme-cubugu@muctebadikmen --scope user
claude plugin uninstall my-skills@muctebadikmen --scope user
claude plugin marketplace remove muctebadikmen

Güvenlik

Modlar Claude Code'un içinde sizin yetkilerinizle çalışır, bu yüzden kurmadan önce bakmanız doğru. Kodun tamamı bu depoda; modlar/<mod>/hooks/ klasörlerinde okuyabilirsiniz. Depoyu indirip bir modu kendiniz de denetleyebilirsiniz:

claude plugin validate modlar/otomatik-devir
claude plugin validate modlar/ilerleme-cubugu

Çıktı, modun hangi işlemleri yaptığını listeler. İki modun listesinde de ağ çağrısı yoktur. ilerleme-cubugu yalnızca proje klasöründeki plan dosyalarını okur, hiçbir dosyaya yazmaz. otomatik-devir devam notunu Claude'a yazdırır (.workflow/handoff/<oturum-kimliği>.md); kendisi mod açıkken sistem prompt'una devri kendisinin yönettiğini söyleyen bir bölüm ekler, eşikte Claude'un süren turuna talimat ekler, alt ajan ve Workflow başlatmayı eşikten sonra reddeder ve devir sürerken alt ajanlar ya da Workflow'lar çalışıyorsa turun bitmesini engeller. Alt sohbetleri ana sohbetteki Claude'a masaüstü uygulamasının oturum aracıyla (start_session) açtırır. Orkestra modu bu sohbet için get_session çağırır ve küçük JSON kayıtlarını ~/.claude/plugins/data/otomatik-devir/orkestra/ altına yazar. Her zincirin eşiğini, sınırını ve durdurma bayrağını ana sohbetin kimliğiyle anahtarlanan tek bir küçük ayar kaydında tutar (dosya olarak ayar-<kimlik>.json, aynı klasörde); genel esik/acik anahtarları artık kullanılmaz. İlk yüklemede eski sürümün otomatik-devir-* zamanlanmış görevlerini siler.

Bilinen sınırlar

  • otomatik-devir: Alt komutlar Türkçe harfsiz yazılır: esik, simdi (eşik çalışmaz). Tur sonu koruması yalnızca alt ajanları ve Workflow'ları bekler; arka plan Bash, Monitor ve geliştirme sunucuları beklenmez. 30 dakikada bitmeyen alt ajanlar durdurulur ve devir dosyasında "Yeniden çalıştır" olarak kalır.
  • Zincir /otomatik-devir:devir-otonom <görev> ile başlar: komut listesinde kısa /devir-otonom adı görünmez; /devir sohbetin ilk mesajından sonra çıkar.
  • Ana sohbet yazdığınız turun içinde kalmalıdır; tur kapanırsa zincir duraklar.
  • Devir dosyasını yazmadan ve bitmeden çalışmayı bırakan alt sohbet yaklaşık 10 dakikada fark edilir: zincir Orkestra durdu: alt sohbet N yanıt vermiyor ile durur ve ana sohbet özet yazar.
  • Hâlâ çalışırken takılan alt sohbet ana sohbeti bekletir (Esc, sonra /devir otonom dur).
  • Başlatma çağrısının tam ortasında bir çökme aynı alt sohbetin iki kez açılmasına yol açabilir.
  • /devir kapat kendi zincirini ana sohbetin sonraki adımında durdurur; devir dışında çalışan bir alt sohbet o anki turunu bitirir (öldürülmez).
  • Ana sohbetin kendi bağlamı %80'e gelirse zincir sıradaki alt sohbet sınırında bir özetle biter; özet, hazır devir dosyasından yeni bir zincirde nasıl devam edileceğini söyler.
  • Ayarlar zincire özgüdür: bir zincirin eşiği, sınırı ya da durdurması o zincirin ana sohbetinde ya da alt sohbetlerinden birinde yazılmalıdır. Bir alt sohbet devir yaparken durumu Devir hazır görünür; /devir kapat o devri iptal eder ve ana sohbet sonraki adımında durur.
  • ilerleme-cubugu: Plan dosyasını editörde elle değiştirirseniz çubuğun güncellenmesi birkaç saniye sürebilir. Plan çubuğu yalnız o dosyalardan bahseden sohbette görünür. İş bitince çubuk kısa bir süre "✓ Tamamlandı" gösterip kaybolur.
  • Yazı kutusunun üstündeki şerit paylaşılır: iki mod (ve varsa başka modlar) aynı şeride çizer. Başka modun düğmeleri (ör. "Geç / Bekle") her zaman üstte kalır; adım listesi açıkken bile onları ekrandan itmez.

Geliştirenler için

Her modun testleri modlar/<mod>/tests/ içinde. Çalıştırmak için mod klasöründe:

claude plugin test .

Lisans

MIT. Kullanın, değiştirin, paylaşın. Sorun görürseniz bir issue açın ya da Skool topluluğunda yazın.

Source 3 files
hooks/register.tsx 444 lines
1import { atom, read, update } from 'claude-code'
2import type { EngineInterface, Register, RenderElement, RenderInput, Timer } from 'claude-code'
3
4import type { IlerlemeCubuguAdim as Adim, IlerlemeCubuguDurum as Durum } from '../types'
5import {
6  genericSteps,
7  ledgerUnread,
8  mergeProgress,
9  mySkillSteps,
10  parseMsPlan,
11  parseProgress,
12  parseState,
13  planDirsFromState,
14} from './progress'
15import type { MsPlan } from './progress'
16
17const tasks = atom({ plugin: 'ilerleme-cubugu', key: 'tasks' } as const, [])
18const plan = atom({ plugin: 'ilerleme-cubugu', key: 'plan' } as const, [])
19const job = atom({ plugin: 'ilerleme-cubugu', key: 'job' } as const, { startedAt: null, doneAt: null })
20const isHidden = atom({ plugin: 'ilerleme-cubugu', key: 'isHidden' } as const, false)
21const isExpanded = atom({ plugin: 'ilerleme-cubugu', key: 'isExpanded' } as const, false)
22const engagedSid = atom({ plugin: 'ilerleme-cubugu', key: 'engagedSid' } as const, null)
23const isUnread = atom({ plugin: 'ilerleme-cubugu', key: 'isUnread' } as const, false)
24
25const HIDE_MS = 4000
26const TICK_MS = 5000
27const MAX_CELLS = 20
28const USAGE = 'Kullanım: /ilerleme gizle | göster | detay'
29const UNREAD = '⚠ ilerleme kaydı okunamadı · '
30// a text or tool argument that names the my-skill workflow files
31const WORKFLOW = /\b(?:PLAN|STATE|PROGRESS)\.md\b|\bHANDOFF\b|\.workflow\/plans\//
32const ENGAGING_SKILLS = new Set(['my-skill-execute', 'my-skill-handoff', 'my-skill-masterplan'])
33
34type $ = EngineInterface
35type Args = Record<string, unknown>
36
37const text = (value: unknown) => (typeof value === 'string' ? value.trim() : '')
38
39const toStatus = (value: unknown): Durum | 'deleted' | undefined =>
40  value === 'pending' || value === 'in_progress' || value === 'completed' || value === 'deleted'
41    ? value
42    : undefined
43
44const isDone = (step: Adim) => step.status === 'completed'
45
46const isRunning = (step: Adim) => step.status === 'in_progress'
47
48const fromTodos = (todos: unknown): Adim[] =>
49  (Array.isArray(todos) ? todos : []).flatMap((todo: Args, i) => {
50    const content = text(todo?.content)
51    const status = toStatus(todo?.status)
52    if (!content || !status || status === 'deleted') return []
53    return [{ id: `todo-${i}`, content, activeForm: text(todo.activeForm), status }]
54  })
55
56const createdId = (ran: { result?: unknown; text?: string }) => {
57  const result = (ran.result ?? {}) as Args
58  const task = (result.task ?? {}) as Args
59  const id = task.id ?? result.id ?? result.taskId
60  if (typeof id === 'string' || typeof id === 'number') return String(id)
61  return /#(\w+)/.exec(ran.text ?? '')?.[1]
62}
63
64const upsert = (list: Adim[], step: Adim) => {
65  const startsOver = list.length > 0 && list.every(isDone)
66  const base = startsOver ? [] : list
67  const twin = base.findIndex(
68    one => one.id === step.id || (one.id.startsWith('tu:') && one.content === step.content),
69  )
70  if (twin === -1) return [...base, step]
71  return base.map((one, i) => (i === twin ? { ...one, id: step.id } : one))
72}
73
74const patch = (list: Adim[], id: string, args: Args) => {
75  const status = toStatus(args.status)
76  if (status === 'deleted') return list.filter(one => one.id !== id)
77  return list.map(one =>
78    one.id !== id
79      ? one
80      : {
81          ...one,
82          status: status ?? one.status,
83          content: text(args.subject) || one.content,
84          activeForm: text(args.activeForm) || one.activeForm,
85        },
86  )
87}
88
89const bar = (done: number, total: number) => {
90  const cells = Math.min(total, MAX_CELLS)
91  const filled = Math.round((done / total) * cells)
92  return '▓'.repeat(filled) + '░'.repeat(cells - filled)
93}
94
95const clip = (value: string, room: number) =>
96  value.length <= room ? value : `${value.slice(0, Math.max(1, room - 1))}…`
97
98type Found = { path: string; mtimeMs: number }
99
100const STATE_PATH = '.workflow/STATE.md'
101const planPath = (dir: string) => `.workflow/plans/${dir}/PLAN.md`
102const progressPath = (dir: string) => `.workflow/plans/${dir}/PROGRESS.md`
103
104const statFile = ($: $, path: string): Promise<Found | undefined> =>
105  $.fs.stat(path).then(
106    stat => (stat.kind === 'file' ? { path, mtimeMs: stat.mtimeMs } : undefined),
107    () => undefined,
108  )
109
110const newest = (list: (Found | undefined)[]) =>
111  list.filter(one => one !== undefined).sort((a, b) => b.mtimeMs - a.mtimeMs)
112
113let seen = ''
114// one interval per process: a repeated session.start replaces it, never stacks a second one
115let ticker: Timer | undefined
116
117// File I/O only; the parsing is in ./progress (pure, unit-tested). Order (spec §2.1):
118// a my-skill plan (the one STATE.md names, else the newest .workflow/plans/*/PLAN.md)
119// with its status from its PROGRESS.md ledger, else from STATE.md; then the generic ladder on PLAN.md,
120// .workflow/PLAN.md, STATE.md and the newest plan, newest first.
121async function refreshPlan($: $) {
122  const entries = await $.fs.list('.workflow/plans').catch(() => [])
123  const dirs = entries.filter(entry => entry.kind === 'dir').map(entry => entry.name)
124  const plans = await Promise.all(dirs.map(dir => statFile($, planPath(dir))))
125  const ledgers = await Promise.all(dirs.map(dir => statFile($, progressPath(dir))))
126  const fixed = await Promise.all(['PLAN.md', '.workflow/PLAN.md', STATE_PATH].map(path => statFile($, path)))
127
128  // re-read only when any file consulted changed (or appeared, or went away)
129  const stamp = newest([...plans, ...ledgers, ...fixed])
130    .map(one => `${one.path}:${one.mtimeMs}`)
131    .sort()
132    .join('|')
133  if (stamp === seen) return
134
135  const texts = new Map<string, Promise<string>>()
136  const load = (path: string) => {
137    if (!texts.has(path)) texts.set(path, $.fs.read(path).catch(() => ''))
138    return texts.get(path) as Promise<string>
139  }
140
141  const state = fixed[2]
142  const stateText = state ? await load(STATE_PATH) : ''
143  const [active] = newest(plans)
144  const named = state ? planDirsFromState(stateText, dirs.filter((_, i) => plans[i] !== undefined)) : []
145
146  let mine: { plan: MsPlan; found: Found; isNamed: boolean; dir: string } | undefined
147  for (const dir of named) {
148    const found = plans[dirs.indexOf(dir)]
149    const parsed = found && parseMsPlan(await load(found.path))
150    if (found && parsed) {
151      mine = { plan: parsed, found, isNamed: true, dir }
152      break
153    }
154  }
155  if (!mine && active) {
156    const parsed = parseMsPlan(await load(active.path))
157    if (parsed) mine = { plan: parsed, found: active, isNamed: false, dir: dirs[plans.indexOf(active)] ?? '' }
158  }
159
160  let steps: Adim[] = []
161  let unread = false
162  if (mine) {
163    // an unnamed plan newer than STATE.md is not what STATE.md's ids are about
164    const credit = state !== undefined && (mine.isNamed || state.mtimeMs >= mine.found.mtimeMs)
165    const ids = new Set(mine.plan.ids)
166    const status = credit ? parseState(stateText, ids) : undefined
167    // the plan's own ledger always belongs to it, and decides over STATE.md (Decision 6)
168    const ledger = ledgers[dirs.indexOf(mine.dir)]
169    if (ledger) {
170      steps = mySkillSteps(mine.plan, mergeProgress(parseProgress(await load(ledger.path), ids), status))
171    } else {
172      steps = mySkillSteps(mine.plan, status)
173      unread = status !== undefined && ledgerUnread(status)
174    }
175  }
176  // an all-done my-skill plan yields to anything else open; kept, it lets reconcile
177  // flash "✓ Tamamlandı" for a job it saw run
178  if (steps.every(one => one.status === 'completed')) {
179    const skip = new Set([mine?.found.path, mine?.isNamed ? STATE_PATH : undefined])
180    for (const { path } of newest([...fixed, active])) {
181      if (skip.has(path)) continue
182      const found = genericSteps(await load(path), path === STATE_PATH)
183      if (found.length > 0 && (steps.length === 0 || found.some(one => one.status !== 'completed'))) {
184        steps = found
185        // the safety net is about the my-skill plan, not the file that replaced it
186        unread = false
187        break
188      }
189    }
190  }
191
192  seen = stamp
193  await update($, plan, () => steps)
194  await update($, isUnread, () => unread)
195}
196
197const sessionId = ($: $) => $.session.id().catch(() => '')
198
199// The plan-file bar belongs to the conversation that engaged it (a prompt naming the
200// workflow files, an engaging skill, a tool call on them); a task list always does.
201async function isEngaged($: $) {
202  const sid = await read($, engagedSid)
203  return sid !== null && sid === (await sessionId($))
204}
205
206async function engage($: $) {
207  const sid = await sessionId($)
208  await update($, engagedSid, () => sid)
209  await refreshPlan($)
210  await reconcile($)
211}
212
213async function activeSteps($: $) {
214  const fromTasks = await read($, tasks)
215  if (fromTasks.length > 0) return fromTasks
216  return (await isEngaged($)) ? await read($, plan) : []
217}
218
219async function reconcile($: $) {
220  const steps = await activeSteps($)
221  const before = await read($, job)
222  const now = await $.clock.now()
223  let after = before
224
225  if (steps.length === 0) {
226    after = { startedAt: null, doneAt: null }
227  } else if (!steps.every(isDone)) {
228    if (before.startedAt === null || before.doneAt !== null) after = { startedAt: now, doneAt: null }
229  } else if (before.startedAt !== null && before.doneAt === null) {
230    after = { startedAt: before.startedAt, doneAt: now }
231    $.ui.toast('✓ Tamamlandı')
232    $.clock.after(HIDE_MS + 100, () => $.ui.invalidate('ui.render'))
233  }
234
235  if (after !== before) await update($, job, () => after)
236}
237
238async function tick($: $) {
239  if ((await read($, tasks)).length === 0 && (await isEngaged($))) await refreshPlan($)
240  await reconcile($)
241}
242
243const isOtherSession = async ($: $, id: string | undefined) => {
244  const sid = await sessionId($)
245  return Boolean(id) && Boolean(sid) && id !== sid
246}
247
248export const register: Register = on => {
249  on('session.start', async ($, e, next) => {
250    await $.command.register({
251      name: 'ilerleme',
252      description: 'İlerleme çubuğunu gizler, gösterir ya da adım listesini açar',
253      argumentHint: 'gizle | göster | detay',
254      immediate: true,
255    })
256    ticker?.cancel()
257    ticker = $.clock.every(TICK_MS, () => void tick($).catch(() => undefined))
258    await tick($).catch(() => undefined)
259
260    return next(e)
261  })
262
263  on('command.run', { command: 'ilerleme' }, async ($, e) => {
264    // "GİZLE", "GIZLE", "Göster" and "goster" all work
265    const arg = e.args.trim().toLocaleLowerCase('tr').replace(/ı/g, 'i')
266
267    if (arg === 'gizle') {
268      await update($, isHidden, () => true)
269      return { text: 'İlerleme çubuğu gizlendi. Geri getirmek için: /ilerleme göster' }
270    }
271    if (arg === 'göster' || arg === 'goster') {
272      await update($, isHidden, () => false)
273      return { text: 'İlerleme çubuğu gösteriliyor.' }
274    }
275    if (arg === 'detay') {
276      const open = await update($, isExpanded, value => !value)
277      return { text: open ? 'Adım listesi açıldı.' : 'Adım listesi kapatıldı.' }
278    }
279
280    return { text: USAGE }
281  })
282
283  on('tool.call', async ($, e, next) => {
284    const ran = await next(e)
285    if (ran.deny !== undefined || ran.isError === true) return ran
286
287    const tool = String(e.tool)
288    const args = e as unknown as Args
289    // TaskCreate/TaskUpdate share the session's single task list, so a sub-agent's
290    // calls count; a sub-agent's TodoWrite is its own private list and must not
291    // replace the main one.
292    if (tool === 'TodoWrite' && e.agentId !== undefined) return ran
293
294    try {
295      if (tool === 'TodoWrite') {
296        await update($, tasks, () => fromTodos(args.todos))
297      } else if (tool === 'TaskCreate') {
298        const id = createdId(ran) ?? `tu:${e.tool_use_id}`
299        const step: Adim = {
300          id,
301          content: text(args.subject) || text(args.description),
302          activeForm: text(args.activeForm),
303          status: 'pending',
304        }
305        await update($, tasks, list => upsert(list, step))
306      } else if (tool === 'TaskUpdate') {
307        await update($, tasks, list => patch(list, String(args.taskId), args))
308      } else if (Object.values(args).some(value => typeof value === 'string' && WORKFLOW.test(value))) {
309        await engage($)
310        return ran
311      } else {
312        return ran
313      }
314      await reconcile($)
315    } catch {
316      // the tool already ran; a failed progress update must not fail it
317    }
318
319    return ran
320  })
321
322  on('prompt.submit', async ($, e, next) => {
323    const ran = await next(e)
324    if (ran.drop === undefined && WORKFLOW.test(e.text)) await engage($).catch(() => undefined)
325
326    return ran
327  })
328
329  on('skill.prompt', async ($, e, next) => {
330    const ran = await next(e)
331    if (ENGAGING_SKILLS.has(e.skill.split(':').pop() ?? '')) await engage($).catch(() => undefined)
332
333    return ran
334  })
335
336  on('classic.TaskCreated', async ($, e, next) => {
337    if (await isOtherSession($, e.session_id)) return next(e)
338    const step: Adim = {
339      id: e.task_id,
340      content: e.task_subject,
341      activeForm: '',
342      status: 'pending',
343    }
344    // a failure here must never hold up Claude's own task flow
345    await update($, tasks, list => upsert(list, step))
346      .then(() => reconcile($))
347      .catch(() => undefined)
348
349    return next(e)
350  })
351
352  on('classic.TaskCompleted', async ($, e, next) => {
353    if (await isOtherSession($, e.session_id)) return next(e)
354    await update($, tasks, list => patch(list, e.task_id, { status: 'completed' }))
355      .then(() => reconcile($))
356      .catch(() => undefined)
357
358    return next(e)
359  })
360
361  on('turn.complete', async ($, e, next) => {
362    await tick($).catch(() => undefined)
363
364    return next(e)
365  })
366
367  // A /clear (e.g. otomatik-devir's switch) or a resume goes on in this process as
368  // another conversation, with no session.start: nothing of the old one carries over.
369  on('session.end', async ($, e, next) => {
370    seen = ''
371    await update($, tasks, () => [])
372    await update($, plan, () => [])
373    await update($, job, () => ({ startedAt: null, doneAt: null }))
374    await update($, engagedSid, () => null)
375    await update($, isUnread, () => false)
376
377    return next(e)
378  })
379
380  // AbovePrompt is one band shared with otomatik-devir and blast-radius (its narrow-
381  // terminal fallback). Nothing to show: pass with next(e) untouched. Otherwise compose,
382  // never replace: whatever the plugins beneath drew comes FIRST (a handoff question, a
383  // held command), then this mod's rows, so an opened step list can never push another
384  // mod's buttons out of the band's window. No hotkey, no autoFocus: the keys stay theirs.
385  on('ui.render', { component: 'AbovePrompt' }, async ($, e, next) => {
386    const mine = await ownRows($, e)
387    if (mine === undefined) return next(e)
388
389    const below = await next(e)
390    const { Box } = $.ui.resolve(e)
391    return (
392      <Box flexDirection="column">
393        {below ?? null}
394        {mine}
395      </Box>
396    )
397  })
398}
399
400async function ownRows($: $, e: RenderInput<'AbovePrompt'>): Promise<RenderElement[] | undefined> {
401  if (e.component !== 'AbovePrompt') return undefined
402  if (e.props.hasSurvey || (await read($, isHidden))) return undefined
403
404  const steps = await activeSteps($)
405  const { startedAt, doneAt } = await read($, job)
406  if (steps.length === 0 || startedAt === null) return undefined
407
408  const now = await $.clock.now()
409  const done = steps.filter(isDone).length
410  const isComplete = done === steps.length
411  if (isComplete && (doneAt === null || now - doneAt > HIDE_MS)) return undefined
412
413  const total = steps.length
414  // the safety net speaks for the plan files only, never for a task list
415  const warn = (await read($, tasks)).length === 0 && (await read($, isUnread)) ? UNREAD : ''
416  const head = `${bar(done, total)} ${done}/${total} · %${Math.round((done / total) * 100)} · ${warn}`
417  const running = steps.filter(isRunning)
418  const next = steps.find(one => !isDone(one))
419  const room = Math.max(8, e.props.bodyColumns - head.length - 9)
420  // Decision 7: parallel work is a count; one step is named; none running names the next
421  const middle =
422    isComplete || !next
423      ? '✓ Tamamlandı'
424      : running.length >= 2
425        ? `Şu an ${running.length} iş üzerinde çalışılıyor`
426        : running[0]
427          ? `Şu an: ${clip(running[0].activeForm || running[0].content, room)}`
428          : `Sıradaki: ${clip(next.content, room)}`
429  const expanded = await read($, isExpanded)
430
431  const { Button, Text } = $.ui.resolve(e)
432
433  return [
434    <Button key="toggle" label={head + middle} plain onPress={() => update($, isExpanded, value => !value)} />,
435    ...(expanded
436      ? steps.map(one => (
437          <Text key={`adim-${one.id}`} dimColor={isDone(one)} bold={isRunning(one)} wrap="truncate-end">
438            {isDone(one) ? '✓' : isRunning(one) ? '●' : '○'} {one.content}
439          </Text>
440        ))
441      : []),
442  ]
443}
444
hooks/progress.ts 411 lines
1// Pure parsers for the progress bar: text in, steps out. No I/O here; register.tsx
2// reads the files and hands their text to these functions.
3// Spec: .workflow/research/progress-formats.md (my-skill first, then a generic ladder).
4
5import type { IlerlemeCubuguAdim as Adim, IlerlemeCubuguDurum as Durum } from '../types'
6
7export type MsPlan = {
8  ids: string[]
9  titles: Map<string, string>
10  done: Set<string>
11}
12
13export type StateInfo = {
14  done: Set<string>
15  inProgress: Set<string>
16  phase: string
17  activeSkill: string
18  /** ids retired from the plan (PROGRESS.md `[-]`); left out of the total */
19  dropped?: Set<string>
20  /** non-blank content lines under STATE.md's `## Done` */
21  doneLines?: number
22}
23
24// A plan's own ledger, .workflow/plans/<dir>/PROGRESS.md: one `- [x] T12 — …` line per task.
25export type ProgressInfo = {
26  done: Set<string>
27  inProgress: Set<string>
28  blocked: Set<string>
29  dropped: Set<string>
30  /** any running box (`[~] [>] [/]`) at all; without one STATE.md's In progress stands in */
31  marksRunning: boolean
32}
33
34const MS_ID = /^[ \t]{0,3}[-*+][ \t]+id:[ \t]*([A-Z]{1,3}\d{1,4}[a-z]{0,2})[ \t]*(?:#.*)?$/
35const MS_TITLE = /^[ \t]{2,6}(?:goal|title):[ \t]*(.+)$/
36const MS_STATUS_DONE = /^[ \t]{2,6}status:[ \t]*(?:\[x\][ \t]*)?(?:DONE|done|✅|tamam(?:land[ıi])?)(?!\p{L})/u
37const CHECKED = /^[ \t]{0,3}[-*+][ \t]+\[[xX]\][ \t]+(.*)$/
38const HEADING = /^[ \t]{0,3}(#{1,6})[ \t]+(.*)$/
39const BULLET = /^([ \t]?)[-*+][ \t]+(.*)$/
40const RANGE = /[A-Z]{1,3}\d+[a-z]{0,2}[ \t]*(?:\.\.|–|—|→|-)[ \t]*[A-Z]{1,3}\d+[a-z]{0,2}/g
41const SHA_AFTER = '(?=[ \\t]+(?=[0-9a-f]*\\d)[0-9a-f]{7,40}\\b)'
42const PLAN_PATH = /(?:^|[^\w-])(?:\.workflow\/)?plans\/([^/\s`'")\]]+)\/PLAN\.md/g
43
44const lines = (source: string) => source.replace(/\r\n?/g, '\n').split('\n')
45
46export const plainText = (value: string) => value.replace(/\*\*|__|`|~~/g, '').trim()
47
48// Turkish-aware fold that keeps English words intact (tr's own 'I' → 'ı' would not)
49export const fold = (value: string) => value.replace(/[İI]/g, 'i').toLowerCase()
50
51export type Section = 'done' | 'in_progress' | 'remaining' | 'none'
52
53const SECTION_DONE = /^(done|completed|finished|merged|tamamland|tamamlanan|bitti|biten|yap[ıi]ld[ıi]|yap[ıi]lan|birleş)/
54const SECTION_RUNNING = /^(in[ -]progress|doing|wip|active|devam ediyor|sürüyor|sürmekte|yap[ıi]l[ıi]yor|çal[ıi]ş[ıi]l[ıi]yor|şu an)/
55const SECTION_REMAINING = /^(remaining|to[ -]?do|pending|backlog|next|up next|kalan|yap[ıi]lacak|bekleyen|s[ıi]rada|s[ıi]radaki)/
56
57export const sectionOf = (heading: string): Section => {
58  const name = fold(heading.replace(/^[^\p{L}]+/u, ''))
59  if (SECTION_DONE.test(name)) return 'done'
60  if (SECTION_RUNNING.test(name)) return 'in_progress'
61  if (SECTION_REMAINING.test(name)) return 'remaining'
62  return 'none'
63}
64
65// Calls `visit` for every top-level bullet with the section it sits in, and `onLine`
66// for every other non-blank, non-heading line.
67const walkSections = (
68  source: string,
69  visit: (section: Section, text: string) => void,
70  onLine?: (section: Section) => void,
71) => {
72  let section: Section = 'none'
73  let level = 0
74  for (const line of lines(source)) {
75    const heading = HEADING.exec(line)
76    if (heading) {
77      const depth = (heading[1] ?? '').length
78      const found = sectionOf(heading[2] ?? '')
79      if (found !== 'none' || section === 'none' || depth <= level) {
80        section = found
81        level = depth
82      }
83      continue
84    }
85    const bullet = BULLET.exec(line)
86    if (bullet) visit(section, bullet[2] ?? '')
87    else if (line.trim()) onLine?.(section)
88  }
89}
90
91const shortTitle = (goal: string) => {
92  const text = plainText(goal)
93  const cuts = [' (AUD-', '. ', '; '].map(mark => text.indexOf(mark)).filter(at => at > 0)
94  return (cuts.length > 0 ? text.slice(0, Math.min(...cuts)) : text).trim()
95}
96
97const idPattern = (ids: Iterable<string>, tail = '') => {
98  const sorted = [...ids].sort((a, b) => b.length - a.length)
99  return new RegExp(`(?<![\\w/.\\-])(${sorted.join('|')})(?![\\w\\-/])${tail}`, 'g')
100}
101
102const idsIn = (text: string, pattern: RegExp) => [...text.matchAll(pattern)].map(match => match[1] ?? '')
103
104// a parenthetical that qualifies a label: "Session 4 (ids in x.txt): T1 T2"
105const LABEL_NOTE = /\([^()]*\)(?=[ \t]*:)/g
106// what may sit between the ids of a bare list ("T90, T300 and T267.")
107const LIST_REST = /^(?:[\s,.&+]|\band\b|\bve\b)*$/
108
109// `;`-separated clauses, outside parentheses
110const clauses = (text: string) => {
111  const found: string[] = []
112  let depth = 0
113  let from = 0
114  for (let i = 0; i < text.length; i++) {
115    const char = text[i]
116    if (char === '(') depth++
117    else if (char === ')') depth = Math.max(0, depth - 1)
118    else if (char === ';' && depth === 0) {
119      found.push(text.slice(from, i))
120      from = i + 1
121    }
122  }
123  found.push(text.slice(from))
124  return found
125}
126
127const headOf = (clause: string) => clause.replace(RANGE, ' ').split(/ — | – | - |\(/)[0] ?? ''
128
129// The ids a bullet is about: its head, before the first dash or parenthesis; of its
130// colon segments, the first that names a plan id ("W4: T1 T15" → T1 T15). A later
131// `;` clause adds its ids only when it is a bare id list ("…: T1 (x); T2, T3 (y)").
132export const leadIds = (bullet: string, ids: Set<string>) => {
133  if (ids.size === 0) return []
134  const pattern = idPattern(ids)
135  const text = plainText(bullet.replace(/^\[[^\]]\][ \t]*/, '')).replace(LABEL_NOTE, '')
136  const [first = '', ...rest] = clauses(text)
137  const found: string[] = []
138  for (const segment of headOf(first).split(':')) {
139    const some = idsIn(segment, pattern)
140    if (some.length > 0) {
141      found.push(...some)
142      break
143    }
144  }
145  for (const clause of rest) {
146    const head = headOf(clause)
147    const some = idsIn(head, pattern)
148    if (some.length > 0 && LIST_REST.test(head.replace(pattern, ' '))) found.push(...some)
149  }
150  return found
151}
152
153// A my-skill plan: `- id: T1` lines (at least two), `goal:` titles, `status: DONE`
154// fields and a `- [x] T1 — …` ledger as the plan's own record of what is done.
155export const parseMsPlan = (source: string): MsPlan | undefined => {
156  const ids: string[] = []
157  const titles = new Map<string, string>()
158  const done = new Set<string>()
159  const ledger: string[] = []
160  let at: string | undefined
161  for (const line of lines(source)) {
162    const id = MS_ID.exec(line)?.[1]
163    if (id) {
164      if (!ids.includes(id)) ids.push(id)
165      at = id
166      continue
167    }
168    const checked = CHECKED.exec(line)
169    if (checked) ledger.push(checked[1] ?? '')
170    if (!at) continue
171    const title = MS_TITLE.exec(line)?.[1]
172    if (title && !titles.has(at)) titles.set(at, shortTitle(title))
173    if (MS_STATUS_DONE.test(line)) done.add(at)
174  }
175  if (ids.length < 2) return undefined
176  const set = new Set(ids)
177  for (const text of ledger) for (const id of leadIds(text, set)) done.add(id)
178  return { ids, titles, done }
179}
180
181// an In progress line about what is held up, not running ("BLOCKED on owner: T245")
182const BLOCKED = /^(blocked|engell?i|bloke)(?!\p{L})/u
183
184// STATE.md, read against a plan's id set: Done (sha pairs + lead ids), In progress
185// (lead ids), and the header's Phase / Active skill. Ids outside the plan are dropped.
186export const parseState = (source: string, ids: Set<string>): StateInfo => {
187  const done = new Set<string>()
188  const inProgress = new Set<string>()
189  let phase = ''
190  let activeSkill = ''
191  for (const line of lines(source)) {
192    const phaseAt = /^Phase:[ \t]*(.*)$/.exec(line)
193    if (phaseAt && !phase) phase = phaseAt[1] ?? ''
194    const skillAt = /^Active skill:[ \t]*(.*)$/.exec(line)
195    if (skillAt && !activeSkill) activeSkill = skillAt[1] ?? ''
196  }
197  let doneLines = 0
198  const withSha = ids.size > 0 ? idPattern(ids, SHA_AFTER) : undefined
199  walkSections(
200    source,
201    (section, text) => {
202      if (section === 'done') doneLines++
203      if (!withSha) return
204      if (section === 'done') {
205        for (const id of idsIn(text.replace(RANGE, ' '), withSha)) done.add(id)
206        for (const id of leadIds(text, ids)) done.add(id)
207      } else if (section === 'in_progress' && !BLOCKED.test(fold(plainText(text.replace(/^\[[^\]]\][ \t]*/, ''))))) {
208        for (const id of leadIds(text, ids)) inProgress.add(id)
209      }
210    },
211    section => {
212      if (section === 'done') doneLines++
213    },
214  )
215  return { done, inProgress, phase, activeSkill, doneLines }
216}
217
218const LEDGER = /^[ \t]*[-*+][ \t]+\[([ xX~>/!-])\][ \t]+(.*)$/
219
220// A ledger line credits only the plan id that is its first token (`- [x] T12 — <sha> — notes`);
221// ids in the notes tail, ranges ("T5–T7") and other prefixes ("AT2", "T1a") never count.
222const ledgerId = (text: string, ids: Set<string>) => {
223  const token = plainText(text).split(/\s/, 1)[0]?.replace(/[:,.;]+$/, '') ?? ''
224  return ids.has(token) ? token : undefined
225}
226
227// PROGRESS.md against a plan's id set: `[x]` done, `[~] [>] [/]` running, `[!]` blocked
228// (neither), `[-]` dropped, `[ ]` pending. Ids outside the plan are ignored; when an id
229// is marked twice, done > dropped > blocked > running.
230export const parseProgress = (source: string, ids: Set<string>): ProgressInfo => {
231  const done = new Set<string>()
232  const inProgress = new Set<string>()
233  const blocked = new Set<string>()
234  const dropped = new Set<string>()
235  let marksRunning = false
236  for (const line of lines(source)) {
237    const match = LEDGER.exec(line)
238    if (!match) continue
239    const mark = match[1] ?? ' '
240    const isRunning = mark === '~' || mark === '>' || mark === '/'
241    if (isRunning) marksRunning = true
242    const into = /[xX]/.test(mark) ? done : mark === '-' ? dropped : mark === '!' ? blocked : isRunning ? inProgress : undefined
243    const id = ledgerId(match[2] ?? '', ids)
244    if (into && id) into.add(id)
245  }
246  const rank = [done, dropped, blocked, inProgress]
247  rank.forEach((set, i) => {
248    for (const lower of rank.slice(i + 1)) for (const id of set) lower.delete(id)
249  })
250  return { done, inProgress, blocked, dropped, marksRunning }
251}
252
253// The status a plan gets when it has a PROGRESS.md (Decision 6): the ledger decides
254// done / dropped / blocked / running; STATE.md (if credited) only gives the phase and
255// active skill, and its In progress while the ledger has no running mark yet.
256export const mergeProgress = (progress: ProgressInfo, state?: StateInfo): StateInfo => {
257  const settled = (id: string) => progress.done.has(id) || progress.dropped.has(id) || progress.blocked.has(id)
258  const inProgress = progress.marksRunning
259    ? progress.inProgress
260    : new Set([...(state?.inProgress ?? [])].filter(id => !settled(id)))
261  return {
262    done: progress.done,
263    inProgress,
264    dropped: progress.dropped,
265    phase: state?.phase ?? '',
266    activeSkill: state?.activeSkill ?? '',
267  }
268}
269
270// The safety net: execute is running, STATE.md's Done says something, yet none of it
271// names a plan id and there is no PROGRESS.md: the bar's count cannot be trusted.
272export const ledgerUnread = (state: StateInfo) =>
273  /^my-skill-execute\b/.test(fold(state.activeSkill)) && (state.doneLines ?? 0) > 0 && state.done.size === 0
274
275const TERMINAL_PHASE = /^(tamam(land[ıi])?|bitti|complete(d)?|done|finished|shipped)(?![\p{L}\d])/u
276
277// Steps for a my-skill plan; [] when no job is active (spec §4). An all-done plan
278// is returned as such, so reconcile can flash "✓ Tamamlandı" for a job it saw run.
279export const mySkillSteps = (plan: MsPlan, state?: StateInfo): Adim[] => {
280  const status = (id: string): Durum =>
281    plan.done.has(id) || state?.done.has(id) ? 'completed' : state?.inProgress.has(id) ? 'in_progress' : 'pending'
282  const steps = plan.ids.filter(id => !state?.dropped?.has(id)).map(id => {
283    const title = plan.titles.get(id)
284    return { id, content: title ? `${id} · ${title}` : id, activeForm: '', status: status(id) }
285  })
286  const done = steps.filter(one => one.status === 'completed').length
287  const running = steps.some(one => one.status === 'in_progress')
288  const skill = fold(state?.activeSkill ?? '')
289  if (!running && TERMINAL_PHASE.test(fold(state?.phase ?? '')) && /^(none|my-skill-ship)\b/.test(skill)) return []
290  if (done === 0 && !running && !/^my-skill-execute\b/.test(skill)) return []
291  return steps
292}
293
294// Which plan dir STATE.md names, best first (spec §2.3 steps 1-3). `dirs` are the
295// existing .workflow/plans/<dir> names; anything else is ignored.
296export const planDirsFromState = (source: string, dirs: string[]): string[] => {
297  const known = new Set(dirs)
298  const found: string[] = []
299  const add = (dir: string | undefined) => {
300    if (dir && known.has(dir) && !found.includes(dir)) found.push(dir)
301  }
302  const all = lines(source)
303
304  for (const line of all) {
305    const plan = /^\s*[-*]?\s*Plan:\s*(\S+)/.exec(line)?.[1]
306    if (plan) add(/(?:^|\/)plans\/([^/\s`'")\]]+)\/PLAN\.md/.exec(plan)?.[1])
307  }
308
309  const counts = new Map<string, number>()
310  const inFiles = new Set<string>()
311  let isFiles = false
312  for (const line of all) {
313    const heading = HEADING.exec(line)
314    if (heading) isFiles = /^files\b/.test(fold(heading[2] ?? ''))
315    for (const match of line.matchAll(PLAN_PATH)) {
316      const dir = match[1] ?? ''
317      counts.set(dir, (counts.get(dir) ?? 0) + 1)
318      if (isFiles) inFiles.add(dir)
319    }
320  }
321  const mentioned = [...counts.keys()]
322  ;[...mentioned]
323    .sort((a, b) => Number(inFiles.has(b)) - Number(inFiles.has(a)) || (counts.get(b) ?? 0) - (counts.get(a) ?? 0))
324    .forEach(add)
325
326  const header = all.slice(0, Math.max(0, all.findIndex(line => /^##\s/.test(line)))).join('\n') || source
327  const goal = all.filter(line => /^Goal:/.test(line)).join('\n')
328  for (const text of [goal, header]) {
329    for (const dir of dirs) {
330      if (text.includes(`${dir} PLAN.md`) || text.includes(`plans/${dir}/`)) add(dir)
331    }
332  }
333  return found
334}
335
336// --- generic ladder (spec §5) ---
337
338// any indent, as before the my-skill parser: nested sub-task boxes count too
339const BOX = /^[ \t]*[-*+][ \t]+\[([ xX✓✔~>/.-])\][ \t]+(.*)$/
340
341// L1 (and L4's checkbox part): `[x]` done, `[~] [>] [/] [.]` running, `[-]` dropped;
342// an open box under an in-progress heading is running.
343export const checkboxSteps = (source: string): Adim[] => {
344  let section: Section = 'none'
345  return lines(source).flatMap((line, i) => {
346    const heading = HEADING.exec(line)
347    if (heading) {
348      section = sectionOf(heading[2] ?? '')
349      return []
350    }
351    const match = BOX.exec(line)
352    if (!match) return []
353    const mark = match[1] ?? ' '
354    if (mark === '-') return []
355    const status: Durum = /[xX✓✔]/.test(mark)
356      ? 'completed'
357      : mark !== ' ' || section === 'in_progress'
358        ? 'in_progress'
359        : 'pending'
360    return [{ id: `plan-${i}`, content: plainText(match[2] ?? ''), activeForm: '', status }]
361  })
362}
363
364// whole words only: "tamamlanmadı" (not finished) and "tamamen" are no done marks
365const MARK_DONE = /✅|✔|☑|\bDONE\b|\[done\]|\(done\)|(?<!\p{L})(tamam(?:land[ıi])?|bitti)(?!\p{L})/u
366const MARK_RUNNING = /🔄|⏳|🚧|\bIN PROGRESS\b|\[wip\]|devam ediyor|sürüyor|←\s*(now|current|şimdi)/u
367const NUMBERED_HEADING =
368  /^[ \t]{0,3}#{2,4}[ \t]+(?:(?:Task|Step|Görev|Adım|Faz|Phase|Aşama)[ \t]+)?(\d+|[A-Z]\d+)[.):\-—][ \t]*(.+)$/
369const ORDERED = /^[ \t]{0,3}(\d+)[.)][ \t]+(.+)$/
370
371const markOf = (title: string): Durum | undefined =>
372  /^~~/.test(title.trim()) || MARK_DONE.test(title) ? 'completed' : MARK_RUNNING.test(title) ? 'in_progress' : undefined
373
374// L2: numbered headings or an ordered list, only with ≥3 items and ≥1 status marker.
375export const numberedSteps = (source: string): Adim[] => {
376  for (const pattern of [NUMBERED_HEADING, ORDERED]) {
377    const items = lines(source).flatMap((line, i) => {
378      const title = pattern.exec(line)?.[2]
379      return title ? [{ i, title, mark: markOf(title) }] : []
380    })
381    if (items.length >= 3 && items.some(item => item.mark !== undefined)) {
382      return items.map(({ i, title, mark }) => ({
383        id: `plan-${i}`,
384        content: plainText(title),
385        activeForm: '',
386        status: mark ?? 'pending',
387      }))
388    }
389  }
390  return []
391}
392
393// L4's fallback: a STATE.md with sections but no checkboxes; plain top-level bullets.
394export const stateBulletSteps = (source: string): Adim[] => {
395  const steps: Adim[] = []
396  const status = { done: 'completed', in_progress: 'in_progress', remaining: 'pending' } as const
397  walkSections(source, (section, text) => {
398    if (section === 'none') return
399    steps.push({ id: `plan-${steps.length}`, content: plainText(text), activeForm: '', status: status[section] })
400  })
401  return steps.length >= 2 ? steps : []
402}
403
404export const genericSteps = (source: string, isState: boolean): Adim[] => {
405  const boxes = checkboxSteps(source)
406  if (boxes.length > 0) return boxes
407  const numbered = numberedSteps(source)
408  if (numbered.length > 0) return numbered
409  return isState ? stateBulletSteps(source) : []
410}
411
types/index.d.ts 27 lines
1export type IlerlemeCubuguDurum = 'pending' | 'in_progress' | 'completed'
2
3export type IlerlemeCubuguAdim = {
4  id: string
5  content: string
6  activeForm: string
7  status: IlerlemeCubuguDurum
8}
9
10export type IlerlemeCubuguIs = { startedAt: number | null; doneAt: number | null }
11
12declare module 'claude-code' {
13  interface PluginState {
14    'ilerleme-cubugu': {
15      tasks: IlerlemeCubuguAdim[]
16      plan: IlerlemeCubuguAdim[]
17      job: IlerlemeCubuguIs
18      isHidden: boolean
19      isExpanded: boolean
20      /** the session id of the conversation that engaged the plan-file bar */
21      engagedSid: string | null
22      /** execute runs a plan whose STATE.md Done names no plan id and that has no PROGRESS.md */
23      isUnread: boolean
24    }
25  }
26}
27