Files
digital-khalifah/generate.py
T

195 lines
10 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
#!/usr/bin/env python3
"""
Generate "The Digital Khalifah: Stewardship at Scale" — Org Sprint Playbook
Dual Mentors: ORG_DESIGNER (Laloux/Teal) + KHALIFAH (Classical Khilafah)
10 Organizational Sprints. Each = Charter → Structure → Authority → Treasury → Shura → Stewardship → Conflict → Succession → Hisbah → Legacy
Two-part generation per chapter to bypass token limits.
"""
import json, os, sys, time, urllib.request, urllib.error
OUTPUT_DIR = os.path.expanduser("~/odysseus_book/digital_khalifah/chapters")
API_URL = "https://opencode.ai/zen/v1/chat/completions"
API_KEY = "sk-jl41MVxfeWRY4ElO7cWXw8ZM6KN5r0S1DG3vK2i1SaUsVdj13ilSxyRdIQLz1Csy"
# Load manifest
with open(os.path.join(os.path.dirname(__file__), "manifest.json")) as f:
MANIFEST = json.load(f)
CHAPTER_SPECS = MANIFEST["org_sprints"]
SYSTEM_PROMPT = f"""You are a master writer creating an ORGANIZATIONAL PLAYBOOK in the style of Frederic Laloux's "Reinventing Organizations" fused with CLASSICAL KHILAFAH/STEWARDSHIP methodology.
DUAL MENTORS:
1. **ORG_DESIGNER** — Organizational Designer (Frederic Laloux / Frederic Laloux / Aaron Dignan style). Voice: "Self-management over hierarchy. Evolutionary purpose over prediction. Wholeness over role-playing." Frameworks: Teal Organizations, Sociocracy, Holacracy, Sociocracy 3.0, Reinventing Organizations, Brave New Work.
2. **KHALIFAH** — Classical Steward (Khalifah) — Classical Khilafah/Stewardship. Voice: "Authority is amanah (trust), not power. Treasury is baitul mal (public trust), not private purse. Shura is method, not ceremony." Frameworks: Classical Khilafah, Siyar, Siyasa Shar'iyyah, Baitul Mal, Hisbah, Shura, Maqasid al-Shariah.
PLAYBOOK FORMAT — EACH CHAPTER = 1 ORGANIZATIONAL SPRINT:
Each chapter follows the ORG SPRINT METHODOLOGY:
1. **CHARTER** (Mithaq / Constitution) — The organizational covenant
2. **STRUCTURE** (Hikma / Architecture) — Circles, roles, domains
3. **AUTHORITY** (Ikhtiyar / Delegation) — Distributed authority, consent-based
3. **TREASURY** (Baitul Mal / Trust) — Revenue, allocation, transparency
4. **SHURA** (Consultation / Consent) — Decision-making at scale
5. **STEWARDSHIP** (Amanah / Trust) — Fiduciary duty, succession
6. **CONFLICT** (Sulh / Reconciliation) — Conflict as growth
7. **SUCCESSION** (Istikhlaf / Continuity) — Pipeline, documentation
8. **HISBAH** (Accountability / Guidance) — Self-regulation at scale
9. **LEGACY** (Waqf / Endowment) — Perpetuity over exit
WRITING STYLE — PLAYBOOK FORMAT (Laloux × Classical Khilafah):
1. **THE CHARTER** (200 words): The organizational covenant. Mithaq. "We the people of this organization..."
2. **SPRINT STRUCTURE** (300 words): ORG_DESIGNER proposes modern structure. KHALIFAH maps to classical precedent. Frameworks visual: "Draw four circles. Label them..."
3. **AUTHORITY MAP** (300 words): Ikhtiyar (delegation) vs Command. Consent vs Command. Frameworks: Sociocracy consent, Classical ikhtiyar.
4. **THE PRINCIPLE (HUKM)** (300 words): The Organizational Principle. Format: Hukm (Ruling), Daleel (Evidence), Maqsad (Purpose), Shurut (Conditions), Munkathirat (Nullifiers). This IS the Organizational Policy.
7. **THE PROTOCOL** (200 words): Exactly 3 steps. Actionable THIS SPRINT. "STEP 1: ... STEP 2: ... STEP 3: ..." Sprint retrospective style.
8. **MUHASABA (RETROSPECTIVE)** (150 words): One piercing question. "What did we learn? What would we change?"
VOICE RULES:
- Playbook tone: Practical. Actionable. No fluff. "Do this Sprint."
- Dual mentor labels: "ORG_DESIGNER:" / "KHALIFAH:" — every exchange labeled.
- Frameworks described visually: "Draw four circles. Label them..."
- Principle format: Hukm / Daleel / Maqsad / Shurut / Munkathirat — use these exact terms.
- Maqasid references: Hifz al-Din, Hifz al-Nafs, Hifz al-Aql, Hifz al-Mal, Hifz al-Nasl.
- Classical terms: Mithaq, Bayt al-Mal, Shura, Ikhtiyar, Amanah, Sulh, Istikhlaf, Hisbah, Waqf, Mithaq, Munkathir.
- Org terms: Circle, Role, Domain, Consent, Objection, Tension, Proposal, Governance, Operational, Strategy, OKR, KPI, Sprint, Retrospective.
- NO academic tone. NO flowery prose. Punchy. Practical. Provocative.
- Audience: Muslim founders, org designers, tech leads, DAO builders building orgs with Islamic first principles.
TARGET: ~2,500 words per chapter (Charter 200 + Structure 300 + Authority 300 + Treasury 200 + Shura 200 + Stewardship 200 + Conflict 200 + Succession 200 + Hisbah 200 + Legacy 200 = ~2,500)
"""
# Build prompts from manifest
CHAPTER_SPECS = MANIFEST["org_sprints"]
CHAPTER_PROMPTS_PART1 = {}
CHAPTER_PROMPTS_PART2 = {}
for spec in MANIFEST["org_sprints"]:
cid = spec["id"]
CHAPTER_PROMPTS_PART1[cid] = f"""Write the FIRST HALF of Sprint #{cid}: "{spec['title']}" — {spec['subtitle']}
FRAMEWORK: {spec['framework']}
MAQSAD: {spec['subtitle'].split('→')[1].strip() if '→' in spec['subtitle'] else 'Preservation of Purpose'}
PART 1 STRUCTURE (target ~1,300 words):
1. THE CHARTER (~200 words):
The organizational covenant. "We the people of this organization..."
Use this charter prompt as inspiration: {spec['charter_prompt']}
2. SPRINT STRUCTURE (~300 words):
ORG_DESIGNER proposes modern structure (Teal/Holacracy/Sociocracy). KHALIFAH maps to classical precedent (Khilafah/Baytu al-Mal/Shura).
Use this charter prompt as inspiration: {spec['charter_prompt']}
3. AUTHORITY MAP (~300 words):
Ikhtiyar (delegation) vs Command. Consent vs Command. Frameworks: Sociocracy consent, Classical ikhtiyar.
Use this charter prompt as inspiration: {spec['charter_prompt']}
4. TREASURY / BAYTUL MAL (~200 words):
Baitul Mal as trust. Revenue, allocation, transparency.
Use this charter prompt as inspiration: {spec['charter_prompt']}
OUTPUT ONLY PART 1. No Principle. No Protocol. No Muhasaba. End after Treasury section."""
CHAPTER_PROMPTS_PART2[cid] = f"""Write the SECOND HALF of Sprint #{spec['id']}: "{spec['title']}" — {spec['subtitle']}
FRAMEWORK: {spec['framework']}
MAQSAD: {spec['subtitle'].split('→')[1].strip() if '→' in spec['subtitle'] else 'Preservation of Purpose'}
PART 2 STRUCTURE (target ~1,200 words):
5. SHURA / CONSENT (~200 words):
Decision-making at scale. Consent vs Consensus. Sociocracy vs Classical Shura.
Use this shura prompt as inspiration: {spec.get('shura_prompt', 'How do you consult at scale? How does a Khalifah consult?')}
5. STEWARDSHIP / AMANAH (~200 words):
Fiduciary duty, succession, pipeline.
Use this stewardship prompt as inspiration: {spec.get('stewardship_prompt', 'How do you ensure stewardship over ownership?')}
6. CONFLICT / SULH (~200 words):
Conflict as growth. Sulh as retrospective.
Use this conflict prompt as inspiration: {spec.get('conflict_prompt', 'How do you resolve conflict at scale?')}
6. SUCCESSION / ISTIKHLAF (~200 words):
Pipeline, documentation, mentorship.
Use this succession prompt as inspiration: {spec.get('succession_prompt', 'How do you design for continuity?')}
8. HISBAH / ACCOUNTABILITY (~200 words):
Guidance over policing. Observability as guidance.
Use this hisbah prompt as inspiration: {spec.get('hisbah_prompt', 'How do you guide without policing?')}
9. LEGACY / WAQF (~200 words):
Endowment over exit. Perpetuity over exit.
Use this legacy prompt as inspiration: {spec.get('legacy_prompt', 'How do you build for perpetuity?')}
9. THE PRINCIPLE (HUKM) (~300 words):
The Organizational Principle. Format exactly:
**HUKM:** [One-sentence ruling: "We adopt X / We establish Y / We distribute Z"]
**DALEEL:** [Evidence summary — 2-3 sentences summarizing key evidence]
**MAQSAD:** [Purpose/Outcome — which Maqasid is served: Hifz al-Din/Nafs/Aql/Mal/Nasl]
**SHURUT:** [Conditions/Constraints — 3-4 bullet points: success metrics, rollback triggers, constraints]
**MUNKATHIRAT:** [Nullifiers/Rollback triggers — 2-3 bullet points: what invalidates this principle]
7. THE PROTOCOL (~200 words):
Exactly 3 steps. Numbered. Actionable THIS SPRINT.
Format:
STEP 1: [Specific action with timeframe]
STEP 2: [Specific action with timeframe]
STEP 3: [Specific action with timeframe]
8. MUHASABA (RETROSPECTIVE) (~150 words):
One piercing question. Start with "What..." or "Where..." or "When..."
Make it uncomfortable. Make it actionable.
OUTPUT ONLY PART 2. No Charter. No Structure. No Authority. No Treasury. No Shura. No Stewardship. No Conflict. No Succession. No Hisbah. Start with '## SHURA / CONSENT'."""
def call_api(prompt, max_tokens=3000):
data = {
"model": "deepseek-v4-flash",
"messages": [
{"role": "system", "content": SYSTEM_PROMPT},
{"role": "user", "content": prompt}
],
"temperature": 0.85,
"max_tokens": max_tokens
}
headers = {
"Authorization": f"Bearer {API_KEY}",
"Content-Type": "application/json",
"User-Agent": "curl/7.88.1"
}
req = urllib.request.Request(API_URL, data=json.dumps(data).encode(), headers=headers)
with urllib.request.urlopen(req, timeout=90) as resp:
return json.loads(resp.read())["choices"][0]["message"]["content"]
if __name__ == "__main__":
import argparse
parser = argparse.ArgumentParser(description="Generate Digital Khalifah Sprints (two-part)")
parser.add_argument("chapter", nargs="?", type=int, help="Chapter number (1-10)")
parser.add_argument("--part", type=int, choices=[1, 2], help="Part 1 or 2")
args = parser.parse_args()
if not os.path.exists(OUTPUT_DIR):
os.makedirs(OUTPUT_DIR)
chapters = [args.chapter] if args.chapter else list(range(1, 11))
parts = [args.part] if args.part else [1, 2]
for chap_num in chapters:
for part_num in parts:
print(f"\n🔄 Sprint #{chap_num} Part {part_num}...")
prompt = CHAPTER_PROMPTS_PART1[chap_num] if part_num == 1 else CHAPTER_PROMPTS_PART2[chap_num]
try:
content = call_api(prompt, max_tokens=3500)
fname = os.path.join(OUTPUT_DIR, f"Sprint_{chap_num:02d}_Part{part_num}.md")
with open(fname, "w", encoding="utf-8") as f:
f.write(content)
words = len(content.split())
print(f"✅ Sprint #{chap_num} Part {part_num} saved — {words} words")
except Exception as e:
print(f"❌ Error: {e}")
time.sleep(3)
print("\n✅ Generation complete!")