Skill: jose-compu/self-improving-supply-chain (version 1.2.0)

--- name: self-improving-supply-chain description: "Captures forecast errors, supplier risks, logistics delays, inventory mismatches, quality deviations, and demand signal shifts to enable continuous supply chain improvement. Use when: (1) A stockout or backorder event occurs, (2) A delivery SLA is missed, (3) Supplier lead time increases, (4) Quality rejection rate spikes, (5) Demand forecast vs. actual variance exceeds 15%, (6) Warehouse capacity threshold is breached, (7) A procurement or routing decision needs documentation." --- # Self-Improving Supply Chain Skill Log supply chain learnings, disruption patterns, and feature requests to markdown files for continuous improvement. Captures forecast errors, supplier risks, logistics delays, inventory mismatches, quality deviations, and demand signal shifts. Important learnings get promoted to supplier scorecards, safety stock policies, routing playbooks, demand planning models, or quality acceptance criteria. ## First-Use Initialisation Before logging anything, ensure the `.learnings/` directory and files exist in the project or workspace root. If any are missing, create them: ```bash mkdir -p .learnings [ -f .learnings/LEARNINGS.md ] || printf "# Supply Chain Learnings\n\nForecast errors, supplier risks, logistics delays, inventory mismatches, quality deviations, and demand signal shifts captured during operations.\n\n**Categories**: forecast_error | supplier_risk | logistics_delay | inventory_mismatch | quality_deviation | demand_signal_shift\n**Areas**: procurement | inventory | logistics | manufacturing | quality | demand_planning | warehousing\n\n---\n" > .learnings/LEARNINGS.md [ -f .learnings/SUPPLY_CHAIN_ISSUES.md ] || printf "# Supply Chain Issues Log\n\nStockouts, delivery delays, supplier failures, quality rejections, and capacity breaches.\n\n---\n" > .learnings/SUPPLY_CHAIN_ISSUES.md [ -f .learnings/FEATURE_REQUESTS.md ] || printf "# Feature Requests\n\nSupply chain tools, automation capabilities, and operational improvements.\n\n---\n" > .learnings/FEATURE_REQUESTS.md ``` Never overwrite existing files. This is a no-op if `.learnings/` is already initialised. Do not log proprietary supplier pricing, negotiated contract terms, or customer-identifiable order data. Prefer aggregated metrics and redacted summaries over raw PO numbers or customer names. This skill is documentation-only: it does not execute purchases, place orders, trigger procurement transactions, or call external payment systems. If you want automatic reminders, use the opt-in hook workflow described in [Hook Integration](#hook-integration). ## Quick Reference | Situation | Action | |-----------|--------| | Stockout event detected | Log to `.learnings/SUPPLY_CHAIN_ISSUES.md` with category `inventory_mismatch` | | Delivery late or SLA missed | Log to `.learnings/SUPPLY_CHAIN_ISSUES.md` with category `logistics_delay` | | Supplier lead time increased | Log to `.learnings/LEARNINGS.md` with category `supplier_risk` | | Quality rejection or defect spike | Log to `.learnings/SUPPLY_CHAIN_ISSUES.md` with category `quality_deviation` | | Demand forecast off by >15% | Log to `.learnings/LEARNINGS.md` with category `forecast_error` | | Warehouse at or above 90% capacity | Log to `.learnings/SUPPLY_CHAIN_ISSUES.md` with category `inventory_mismatch` | | Demand spike from external signal | Log to `.learnings/LEARNINGS.md` with category `demand_signal_shift` | | Recurring supply chain pattern | Link with `**See Also**`, consider priority bump | | Broadly applicable pattern | Promote to scorecard, policy, playbook, or model | | Reusable operational process | Promote to skill extraction | ## OpenClaw Setup (Recommended) OpenClaw is the primary platform for this skill. It uses workspace-based prompt injection with automatic skill loading. ### Installation **Via ClawdHub (recommended):** ```bash clawdhub install self-improving-supply-chain ``` **Manual:** ```bash git clone https://github.com/jose-compu/self-improving-supply-chain.git ~/.openclaw/skills/self-improving-supply-chain ``` ### Workspace Structure OpenClaw injects these files into every session: ``` ~/.openclaw/workspace/ ├── AGENTS.md # Multi-agent workflows, delegation patterns ├── SOUL.md # Behavioral guidelines, personality, principles ├── TOOLS.md # Tool capabilities, integration gotchas ├── MEMORY.md # Long-term memory (main session only) ├── memory/ # Daily memory files │ └── YYYY-MM-DD.md └── .learnings/ # This skill's log files ├── LEARNINGS.md ├── SUPPLY_CHAIN_ISSUES.md └── FEATURE_REQUESTS.md ``` ### Create Learning Files ```bash mkdir -p ~/.openclaw/workspace/.learnings ``` Then create the log files (or copy from `assets/`): - `LEARNINGS.md` — forecast errors, supplier risks, demand signal shifts - `SUPPLY_CHAIN_ISSUES.md` — stockouts, delays, quality problems, capacity breaches - `FEATURE_REQUESTS.md` — supply chain tools, automation, operational capabilities ### Promotion Targets When supply chain learnings prove broadly applicable, promote them: | Learning Type | Promote To | Example | |---------------|------------|---------| | Supplier performance patterns | Supplier scorecards | "Require dual-source for components >$50K annual spend" | | Inventory buffer patterns | Safety stock policies | "Ocean-freight SKUs carry 3 weeks safety stock" | | Routing optimizations | Routing playbooks | "Divert to Nansha when Yantian queue >5 days" | | Forecast accuracy patterns | Demand planning models | "Apply seasonal index for gift-category Q4 SKUs" | | Quality failure patterns | Quality acceptance criteria | "100% inspection on first shipment from new suppliers" | | Workflow patterns | `AGENTS.md` | "Run inventory reconciliation before reorder point calc" | ### Optional: Enable Hook For automatic reminders at session start: ```bash cp -r hooks/openclaw ~/.openclaw/hooks/self-improving-supply-chain openclaw hooks enable self-improving-supply-chain ``` See `references/openclaw-integration.md` for complete details. --- ## Generic Setup (Other Agents) For Claude Code, Codex, Copilot, or other agents, create `.learnings/` in the project or workspace root: ```bash mkdir -p .learnings ``` Create the files inline using the headers shown above. ### Add reference to agent files Add to `AGENTS.md`, `CLAUDE.md`, or `.github/copilot-instructions.md`: #### Self-Improving Supply Chain Workflow When supply chain disruptions or patterns are discovered: 1. Log to `.learnings/SUPPLY_CHAIN_ISSUES.md`, `LEARNINGS.md`, or `FEATURE_REQUESTS.md` 2. Review and promote broadly applicable learnings to: - Supplier scorecards — performance thresholds, risk tiers, qualification requirements - Safety stock policies — buffer calculations, service level targets, review cadence - Routing playbooks — contingency routes, mode-shift triggers, carrier selection - Demand planning models — seasonal indices, channel mix adjustments, event-driven overlays ## Logging Format ### Learning Entry [LRN-YYYYMMDD-XXX] Append to `.learnings/LEARNINGS.md`: ```markdown ## [LRN-YYYYMMDD-XXX] category **Logged**: ISO-8601 timestamp **Priority**: low | medium | high | critical **Status**: pending **Area**: procurement | inventory | logistics | manufacturing | quality | demand_planning | warehousing ### Summary One-line description of the supply chain insight ### Details Full context: what operational condition was observed, why it matters, what the root cause is, and what the downstream impact was. Include quantified metrics where possible (units, cost, days, fill rate). ### Impact - Units affected: X - Cost impact: $Y - Duration: Z days - Service level impact: from A% to B% ### Suggested Action Specific policy change, process improvement, or operational adjustment to adopt ### Metadata - Source: demand_forecast_review | supplier_communication | warehouse_audit | quality_inspection | order_management | logistics_tracking - SKU/Component: identifier (if applicable) - Supplier: name and code (if applicable) - Related Files: path/to/file.ext - Tags: tag1, tag2 - See Also: LRN-20250110-001 (if related to existing entry) - Pattern-Key: forecast_error.seasonal_miss | supplier_risk.single_source (optional) - Recurrence-Count: 1 (optional) - First-Seen: 2025-01-15 (optional) - Last-Seen: 2025-01-15 (optional) --- ``` **Categories for learnings:** | Category | Use When | |----------|----------| | `forecast_error` | Demand forecast deviates significantly from actuals (MAPE >15%) | | `supplier_risk` | Supplier lead time increase, financial distress, capacity constraint, single-source exposure | | `logistics_delay` | Shipment delay, port congestion, carrier failure, customs hold, routing inefficiency | | `inventory_mismatch` | WMS vs physical count variance, stockout, overstock, expired inventory, capacity breach | | `quality_deviation` | Defect rate spike, inspection failure, non-conformance, recall, specification drift | | `demand_signal_shift` | Unexpected demand change from viral event, channel shift, competitor action, regulation | ### Supply Chain Issue Entry [SCM-YYYYMMDD-XXX] Append to `.learnings/SUPPLY_CHAIN_ISSUES.md`: ```markdown ## [SCM-YYYYMMDD-XXX] category **Logged**: ISO-8601 timestamp **Priority**: high **Status**: pending **Area**: procurement | inventory | logistics | manufacturing | quality | demand_planning | warehousing ### Summary Brief description of the supply chain disruption or issue ### Details What happened, when, where in the supply chain, and what triggered it. ### Impact - Units affected: X - Cost impact: $Y (direct + indirect) - Duration: Z days - Customer impact: fill rate drop, delayed orders, SLA breach ### Mitigation Steps 1. Immediate containment action 2. Short-term workaround 3. Root cause investigation 4. Long-term corrective action ### Root Cause What in the supply chain caused this issue. Include contributing factors. ### Context - Trigger: stockout_event | delivery_sla_miss | supplier_lead_time_increase | quality_rejection_spike | forecast_variance | capacity_breach - Carrier/Supplier: name and code - Route/Lane: origin → destination - SKU/Component: identifiers affected ### Metadata - Reproducible: yes | no | seasonal | event_driven - Related Files: path/to/file.ext - See Also: SCM-20250110-001 (if recurring) --- ``` ### Feature Request Entry [FEAT-YYYYMMDD-XXX] Append to `.learnings/FEATURE_REQUESTS.md`: ```markdown ## [FEAT-YYYYMMDD-XXX] capability_name **Logged**: ISO-8601 timestamp **Priority**: medium **Status**: pending **Area**: procurement | inventory | logistics | manufacturing | quality | demand_planning | warehousing ### Requested Capability What supply chain tool, automation, or capability is needed ### User Context Why it's needed, what workflow it improves, what operational problem it solves ### Complexity Estimate simple | medium | complex ### Suggested Implementation How this could be built: dashboard, integration, alert system, optimization model, workflow automation ### Metadata - Frequency: first_time | recurring - Related Features: existing_tool_or_system --- ``` ## ID Generation Format: `TYPE-YYYYMMDD-XXX` - TYPE: `LRN` (learning), `SCM` (supply chain issue), `FEAT` (feature request) - YYYYMMDD: Current date - XXX: Sequential number or random 3 chars (e.g., `001`, `A7B`) Examples: `LRN-20250415-001`, `SCM-20250415-A3F`, `FEAT-20250415-002` ## Resolving Entries When an issue is resolved, update the entry: 1. Change `**Status**: pending` → `**Status**: resolved` 2. Add resolution block after Metadata: ```markdown ### Resolution - **Resolved**: 2025-01-16T09:00:00Z - **Corrective Action**: policy change / supplier qualification / routing update / safety stock adjustment - **Notes**: Description of what was done and verification of effectiveness ``` Other status values: - `in_progress` — Actively being investigated or mitigated - `wont_fix` — Accepted risk or not actionable (add reason in Resolution notes) - `promoted` — Elevated to scorecard, policy, playbook, or model - `promoted_to_skill` — Extracted as a reusable skill ## Detection Triggers Automatically log when you encounter: **Inventory Below Safety Stock** (→ supply chain issue with inventory_mismatch): - Available stock drops below reorder point - Safety stock consumed with no inbound PO in transit - Allocation conflict between customer orders - WMS alerts for zero-available or negative-available **Delivery Tracking Shows Delay** (→ supply chain issue with logistics_delay): - Carrier tracking shows ETA pushed beyond original commitment - Port congestion reports for origin or destination terminal - Customs hold or inspection delay notification - Mode conversion required (ocean → air) to meet deadline **Supplier Communication Indicating Lead Time Change** (→ learning with supplier_risk): - Supplier notifies of capacity reduction or allocation - Lead time quoted on new PO exceeds historical average by >20% - Supplier financial health downgrade (D&B, credit report) - Force majeure notification from supplier **Quality Inspection Failure Rate >2%** (→ supply chain issue with quality_deviation): - Incoming quality inspection rejection rate exceeds 2% threshold - Customer return rate for quality reasons exceeds 1% - Supplier corrective action request (SCAR) issued - Specification non-conformance on critical dimension **Demand Forecast MAPE >15%** (→ learning with forecast_error): - Monthly MAPE exceeds 15% at SKU-family level - Bias consistently positive (underforecast) or negative (overforecast) for 3+ months - New product launch demand significantly different from analogous forecast - Promotional lift or cannibalization not captured in model **Warehouse Utilization >90%** (→ supply chain issue with inventory_mismatch): - DC utilization exceeds 90% of total capacity - Receiving dock backlog exceeds 48 hours - Put-away queue growing faster than processing rate - Overflow to secondary or temporary storage required ## Priority Guidelines | Priority | When to Use | Supply Chain Examples | |----------|-------------|----------------------| | `critical` | Production line stopped, customer order unfulfillable, safety/recall issue | Factory shut down waiting for parts, complete stockout on top-10 SKU, product recall initiated | | `high` | Stockout imminent, supplier failure likely, major SLA breach | Safety stock below 3 days, sole-source supplier in financial distress, 50+ orders delayed | | `medium` | Forecast accuracy degradation, routing inefficiency, quality trend | MAPE trending up over 3 months, suboptimal carrier selection, rejection rate at 1.5% | | `low` | Process documentation, minor optimization, data cleanup | SOP update needed, rounding error in forecast, warehouse label format change | ## Area Tags Use to filter learnings by supply chain domain: | Area | Scope | |------|-------| | `procurement` | Supplier selection, PO management, contract negotiation, spend analysis, qualification | | `inventory` | Safety stock, reorder points, cycle counting, ABC classification, obsolescence | | `logistics` | Freight, routing, carrier management, customs, last-mile, mode selection | | `manufacturing` | Production planning, BOM management, capacity, yield, changeover | | `quality` | Inspection, SCAR, non-conformance, acceptance criteria, certification | | `demand_planning` | Forecasting, seasonal decomposition, promotional planning, new product introduction | | `warehousing` | Storage, picking, packing, receiving, put-away, layout, capacity | ## Promoting to Permanent Operational Standards When a learning is broadly applicable (not a one-off event), promote it to permanent operational standards. ### When to Promote - Same supplier issue recurs across multiple quarters - Forecast error pattern appears for 3+ SKU families - Logistics delay from same lane or carrier happens 3+ times - Quality issue at same supplier or component recurs - Inventory mismatch pattern found in 2+ distribution centers ### Promotion Targets | Target | What Belongs There | |--------|-------------------| | Supplier scorecards | Performance thresholds, risk tier definitions, qualification requirements | | Safety stock policies | Buffer calculations by sourcing mode, service level targets, review cadence | | Routing playbooks | Contingency routes, mode-shift triggers, carrier escalation matrix | | Demand planning models | Seasonal indices, event overlays, channel mix assumptions | | Quality acceptance criteria | Inspection sampling plans, reject thresholds, first-article requirements | | `AGENTS.md` | Automated operational workflows, pre-reorder checks | ### How to Promote 1. **Distill** the learning into a concise rule or policy statement 2. **Add** to appropriate target (scorecard, policy, playbook, model) 3. **Update** original entry: - Change `**Status**: pending` → `**Status**: promoted` - Add `**Promoted**: safety stock policy` (or `supplier scorecard`, `routing playbook`, `demand model`, `quality criteria`) ### Promotion Examples **Learning** (verbose): > Ocean-freight SKUs experience 10-21 day lead time variability. Existing 2-week > safety stock insufficient — caused 4 stockouts in 6 months. **As safety stock policy** (concise): ```markdown ## Ocean-Freight Safety Stock - Buffer: 3 weeks of average weekly demand - Review: quarterly against actual lead time data - Trigger: adjust if lead time std dev changes >20% ``` **Learning** (verbose): > Port congestion at Yantian added 14 days to 12 containers. Diverting to Nansha > saved 7 days on 4 containers. West Coast routing avoided congestion entirely. **As routing playbook** (actionable): ```markdown ## Yantian Congestion Response 1. Monitor Yantian vessel queue daily via CargoSmart 2. If berthing wait >5 days: divert new bookings to Nansha 3. If congestion >10 days: activate West Coast routing via Long Beach 4. Air-freight top 8 critical SKUs if customer SLA at risk 5. Notify customer service for affected order ETAs ``` ## Recurring Pattern Detection If logging something similar to an existing entry: 1. **Search first**: `grep -r "keyword" .learnings/` 2. **Link entries**: Add `**See Also**: SCM-20250110-001` in Metadata 3. **Bump priority** if issue keeps recurring 4. **Consider systemic fix**: Recurring supply chain issues often indicate: - Missing safety stock buffer (→ adjust policy) - Supplier concentration risk (→ qualification of alternate) - Forecast model gap (→ add decomposition or overlay) - Process gap (→ add SOP or checklist) ## Periodic Review Review `.learnings/` at natural breakpoints: ### When to Review - Before finalizing replenishment plans - After month-end demand review - When the same disruption type appears again - Quarterly during S&OP planning cycle ### Quick Status Check ```bash # Count pending supply chain issues grep -h "Status\*\*: pending" .learnings/*.md | wc -l # List pending high-priority issues grep -B5 "Priority\*\*: high" .learnings/SUPPLY_CHAIN_ISSUES.md | grep "^## \[" # Find learnings for a specific area grep -l "Area\*\*: logistics" .learnings/*.md # Find all supplier risk entries grep -B2 "supplier_risk" .learnings/LEARNINGS.md | grep "^## \[" ``` ### Review Actions - Resolve mitigated issues - Promote recurring patterns to policies and playbooks - Link related entries across files - Extract reusable processes as skills ## Simplify & Harden Feed Ingest recurring supply chain patterns from `simplify-and-harden` into policies or playbooks. 1. For each candidate, use `pattern_key` as the dedupe key. 2. Search `.learnings/LEARNINGS.md` for existing entry: `grep -n "Pattern-Key: <key>" .learnings/LEARNINGS.md` 3. If found: increment `Recurrence-Count`, update `Last-Seen`, add `See Also` links. 4. If not found: create new `LRN-...` entry with `Source: simplify-and-harden`. **Promotion threshold**: `Recurrence-Count >= 3`, seen in 2+ quarters or locations, within 12-month window. Targets: supplier scorecards, safety stock policies, routing playbooks, demand models, `AGENTS.md`. ## Hook Integration Enable automatic reminders through agent hooks. This is **opt-in**. ### Quick Setup (Claude Code / Codex) Create `.claude/settings.json` in your project: ```json { "hooks": { "UserPromptSubmit": [{ "matcher": "", "hooks": [{ "type": "command", "command": "./skills/self-improving-supply-chain/scripts/activator.sh" }] }] } } ``` This injects a supply chain-focused learning evaluation reminder after each prompt (~50-100 tokens overhead). ### Advanced Setup (With Disruption Detection) ```json { "hooks": { "UserPromptSubmit": [{ "matcher": "", "hooks": [{ "type": "command", "command": "./skills/self-improving-supply-chain/scripts/activator.sh" }] }], "PostToolUse": [{ "matcher": "Bash", "hooks": [{ "type": "command", "command": "./skills/self-improving-supply-chain/scripts/error-detector.sh" }] }] } } ``` Enable `PostToolUse` only if you want the hook to inspect command output for stockouts, delays, shortages, defects, and other supply chain disruptions. ### Available Hook Scripts | Script | Hook Type | Purpose | |--------|-----------|---------| | `scripts/activator.sh` | UserPromptSubmit | Reminds to evaluate supply chain learnings after tasks | | `scripts/error-detector.sh` | PostToolUse (Bash) | Triggers on stockouts, delays, shortages, quality issues | See `references/hooks-setup.md` for detailed configuration and troubleshooting. ## Automatic Skill Extraction When a supply chain learning is valuable enough to become a reusable skill, extract it. ### Skill Extraction Criteria | Criterion | Description | |-----------|-------------| | **Recurring** | Same disruption pattern in 2+ quarters or locations | | **Verified** | Status is `resolved` with effective corrective action | | **Non-obvious** | Required investigation or cross-functional coordination | | **Broadly applicable** | Not specific to one SKU or supplier; useful across categories | | **User-flagged** | User says "save this as a skill" or similar | ### Extraction Workflow 1. **Identify candidate**: Learning meets extraction criteria 2. **Run helper** (or create manually): ```bash ./skills/self-improving-supply-chain/scripts/extract-skill.sh skill-name --dry-run ./skills/self-improving-supply-chain/scripts/extract-skill.sh skill-name ``` 3. **Customize SKILL.md**: Fill in template with supply chain-specific content 4. **Update learning**: Set status to `promoted_to_skill`, add `Skill-Path` 5. **Verify**: Read skill in fresh session to ensure it's self-contained ### Extraction Detection Triggers **In conversation**: "This delay keeps happening", "Save this process as a skill", "Every quarter we hit this issue", "We need a standard playbook for this". **In entries**: Multiple `See Also` links, high priority + resolved, `supplier_risk` or `logistics_delay` with broad applicability, same `Pattern-Key` across quarters or DCs. ## Multi-Agent Support | Agent | Activation | Detection | |-------|-----------|-----------| | Claude Code | Hooks (UserPromptSubmit, PostToolUse) | Automatic via error-detector.sh | | Codex CLI | Hooks (same pattern) | Automatic via hook scripts | | GitHub Copilot | Manual (`.github/copilot-instructions.md`) | Manual review | | OpenClaw | Workspace injection + inter-agent messaging | Via session tools | ## Best Practices 1. **Log immediately** — operational context fades fast after disruption resolution 2. **Quantify impact** — always include units, cost, days, and service level metrics 3. **Specify the supply chain node** — supplier, DC, lane, or SKU family affected 4. **Track lead times weekly** — detect trends before they cause stockouts 5. **Validate forecasts monthly** — compare forecast vs. actual at SKU-family level using MAPE and bias 6. **Diversify suppliers** — no single-source for components with >$50K annual spend 7. **Maintain safety stock** — buffer by sourcing mode (ocean 3wk, air 1wk, domestic 1.5wk) 8. **Inspect at receiving** — verify quantity and quality before receipting into WMS 9. **Document routing decisions** — record why a lane or mode was chosen for future reference 10. **Promote aggressively** — if a pattern recurs across 2+ quarters, it deserves a policy ## Gitignore Options **Keep learnings local** (per-team): add `.learnings/` to `.gitignore`. **Track learnings in repo** (organization-wide): don't gitignore — learnings become shared operational knowledge. **Hybrid**: gitignore `.learnings/*.md` but keep `.learnings/.gitkeep`. ## Stackability Contract (Standalone + Multi-Skill) This skill is standalone-compatible and stackable with other self-improving skills. ### Namespaced Logging (recommended for 2+ skills) - Namespace for this skill: `.learnings/supply-chain/` - Keep current standalone behavior if you prefer flat files. - Optional shared index for all skills: `.learnings/INDEX.md` ### Required Metadata Every new entry must include: ```markdown **Skill**: supply-chain ``` ### Hook Arbitration (when 2+ skills are enabled) - Use one dispatcher hook as the single entrypoint. - Dispatcher responsibilities: route by matcher, dedupe repeated events, and rate-limit reminders. - Suggested defaults: dedupe key = `event + matcher + file + 5m_window`; max 1 reminder per skill every 5 minutes. ### Narrow Matcher Scope (supply-chain) Only trigger this skill automatically for supply-chain signals such as: - `lead time|stockout|safety stock|supplier delay|fill rate` - `forecast bias|otif|procurement|lane disruption|inventory` - explicit supply-chain intent in user prompt ### Cross-Skill Precedence When guidance conflicts, apply: 1. `security` 2. `engineering` 3. `coding` 4. `ai` 5. user-explicit domain skill 6. `meta` as tie-breaker ### Ownership Rules - This skill writes only to `.learnings/supply-chain/` in stackable mode. - It may read other skill folders for cross-linking, but should not rewrite their entries.

path: assets/FEATURE_REQUESTS.md
content: # Feature Requests

Supply chain tools, automation capabilities, and operational improvements requested during planning and execution sessions.

**Focus areas**: supplier risk scoring, demand forecasting automation, inventory optimization, warehouse management, logistics routing, quality inspection, procurement workflows, capacity planning.

---


path: assets/ERRORS.md
content: # Supply Chain Issues Log

Stockouts, delivery delays, supplier failures, quality rejections, forecast misses, and capacity breaches captured during supply chain operations.

**Categories**: forecast_error | supplier_risk | logistics_delay | inventory_mismatch | quality_deviation | demand_signal_shift
**Areas**: procurement | inventory | logistics | manufacturing | quality | demand_planning | warehousing
**Statuses**: pending | in_progress | resolved | wont_fix | promoted | promoted_to_skill

## Status Definitions

| Status | Meaning |
|--------|---------|
| `pending` | Not yet addressed |
| `in_progress` | Actively being investigated or mitigated |
| `resolved` | Issue resolved, corrective action taken |
| `wont_fix` | Accepted risk or not actionable (reason in Resolution) |
| `promoted` | Elevated to supplier scorecard, safety stock policy, routing playbook, or demand model |
| `promoted_to_skill` | Extracted as a reusable skill |

## Skill Extraction Fields

When an issue is promoted to a skill, add these fields:

```markdown
**Status**: promoted_to_skill
**Skill-Path**: skills/skill-name
```

Example:
```markdown
## [SCM-20250415-001] logistics_delay

**Logged**: 2025-04-15T10:00:00Z
**Priority**: high
**Status**: promoted_to_skill
**Skill-Path**: skills/ocean-freight-contingency
**Area**: logistics

### Summary
Port congestion at Shenzhen added 14 days to ocean freight transit, causing downstream stockouts
...
```

---


path: assets/SKILL-TEMPLATE.md
content: # Supply Chain Skill Template

Template for creating skills extracted from supply chain learnings. Copy and customize.

---

## SKILL.md Template

```markdown
---
name: skill-name-here
description: "Concise description of the supply chain pattern, risk mitigation, or operational improvement this skill addresses. Include trigger conditions."
---

# Skill Name

Brief introduction: what supply chain problem this skill solves, what operational areas it applies to, and its origin.

## Quick Reference

| Situation | Action |
|-----------|--------|
| [Supply chain trigger] | [Mitigation or process to apply] |
| [Related trigger] | [Alternative approach] |

## Background

Why this supply chain knowledge matters. What disruptions it prevents. What cost savings or service level improvements it provides.

## The Problem

### Scenario

Describe the supply chain situation: demand pattern, supplier behavior, logistics constraint, or inventory condition that leads to the issue.

### Impact

Quantify the impact: stockout duration, excess inventory cost, delayed shipments, customer order fill rate drop, production line downtime.

## Solution

### Corrective Action

Step-by-step process to resolve the immediate issue.

### Preventive Measures

1. Policy change to prevent recurrence
2. Monitoring threshold to detect early
3. Escalation path if threshold breached
4. Backup plan or contingency

## Key Metrics

| Metric | Target | Threshold |
|--------|--------|-----------|
| [Relevant KPI] | [Target value] | [Alert threshold] |

## Common Variations

- **Variation A**: Description and how to handle
- **Variation B**: Description and how to handle

## Areas Affected

| Area | Impact | Mitigation |
|------|--------|------------|
| Procurement | [How it affects sourcing] | [Sourcing mitigation] |
| Inventory | [How it affects stock levels] | [Stock mitigation] |
| Logistics | [How it affects transport] | [Routing mitigation] |

## Gotchas

- Warning or common mistake when applying the solution
- Edge case to watch for (seasonality, regional variation, supplier-specific)

## Related

- Link to related supplier scorecard
- Link to safety stock policy
- Link to demand planning model
- Link to related skill

## Source

Extracted from supply chain learning entry.
- **Learning ID**: LRN-YYYYMMDD-XXX or SCM-YYYYMMDD-XXX
- **Original Category**: forecast_error | supplier_risk | logistics_delay | inventory_mismatch | quality_deviation | demand_signal_shift
- **Area**: procurement | inventory | logistics | manufacturing | quality | demand_planning | warehousing
- **Extraction Date**: YYYY-MM-DD
```

---

## Minimal Template

For simple supply chain skills that don't need all sections:

```markdown
---
name: skill-name-here
description: "What supply chain pattern this addresses and when to apply it."
---

# Skill Name

[Problem statement in one sentence]

## Problem

Describe the supply chain disruption or inefficiency.

## Solution

Step-by-step mitigation and prevention.

## Key Metrics

| Metric | Target |
|--------|--------|
| [KPI] | [Value] |

## Source

- Learning ID: LRN-YYYYMMDD-XXX
```

---

## Naming Conventions

- **Skill name**: lowercase, hyphens for spaces
  - Good: `supplier-diversification`, `safety-stock-optimization`, `ocean-freight-contingency`
  - Bad: `SupplierDiv`, `safety_stock`, `fix1`

- **Description**: Start with action verb, mention the operational area
  - Good: "Prevents single-source supplier risk by maintaining qualified backup suppliers. Use when a critical component has fewer than two approved sources."
  - Bad: "Supplier stuff"

- **Files**:
  - `SKILL.md` — Required, main documentation
  - `scripts/` — Optional, executable tools (forecasting helper, stock calculator)
  - `references/` — Optional, detailed docs
  - `assets/` — Optional, templates

---

## Extraction Checklist

Before creating a skill from a supply chain learning:

- [ ] Issue is verified (status: resolved, corrective action taken)
- [ ] Solution is broadly applicable (not one-off anomaly)
- [ ] Impact is quantified (cost, service level, lead time)
- [ ] Area(s) affected are specified
- [ ] Preventive measures are documented (policy, threshold, escalation)
- [ ] Name follows conventions
- [ ] Description is concise but informative

After creating:

- [ ] Update original learning with `promoted_to_skill` status
- [ ] Add `Skill-Path: skills/skill-name` to learning metadata
- [ ] Test skill by reading it in a fresh session
- [ ] Verify metrics and thresholds are realistic


path: assets/LEARNINGS.md
content: # Supply Chain Learnings

Forecast errors, supplier risks, logistics delays, inventory mismatches, quality deviations, and demand signal shifts captured during supply chain operations.

**Categories**: forecast_error | supplier_risk | logistics_delay | inventory_mismatch | quality_deviation | demand_signal_shift
**Areas**: procurement | inventory | logistics | manufacturing | quality | demand_planning | warehousing
**Statuses**: pending | in_progress | resolved | wont_fix | promoted | promoted_to_skill

## Status Definitions

| Status | Meaning |
|--------|---------|
| `pending` | Not yet addressed |
| `in_progress` | Actively being investigated or mitigated |
| `resolved` | Issue resolved, corrective action taken |
| `wont_fix` | Accepted risk or not actionable (reason in Resolution) |
| `promoted` | Elevated to supplier scorecard, safety stock policy, routing playbook, or demand model |
| `promoted_to_skill` | Extracted as a reusable skill |

## Skill Extraction Fields

When a learning is promoted to a skill, add these fields:

```markdown
**Status**: promoted_to_skill
**Skill-Path**: skills/skill-name
```

Example:
```markdown
## [LRN-20250415-001] forecast_error

**Logged**: 2025-04-15T10:00:00Z
**Priority**: high
**Status**: promoted_to_skill
**Skill-Path**: skills/seasonal-demand-model
**Area**: demand_planning

### Summary
Q4 seasonal demand spike not captured in baseline forecast model, caused 30% understock
...
```

---


path: scripts/activator.sh
content: #!/bin/bash
# Supply Chain Self-Improvement Activator Hook
# Triggers on UserPromptSubmit to remind about supply chain learning capture
# Keep output minimal (~50-100 tokens) to minimize overhead

set -e

cat << 'EOF'
<supply-chain-self-improvement-reminder>
After completing this supply chain task, evaluate if extractable knowledge emerged:
- Stockout or backorder event? → SUPPLY_CHAIN_ISSUES.md [SCM-YYYYMMDD-XXX]
- Delivery delay or SLA miss? → SUPPLY_CHAIN_ISSUES.md (logistics_delay)
- Supplier lead time increase or failure? → LEARNINGS.md (supplier_risk)
- Quality rejection or defect spike? → SUPPLY_CHAIN_ISSUES.md (quality_deviation)
- Forecast miss >15% MAPE? → LEARNINGS.md (forecast_error)
- Demand spike or channel shift? → LEARNINGS.md (demand_signal_shift)
- Warehouse capacity >90%? → SUPPLY_CHAIN_ISSUES.md (inventory_mismatch)

If recurring pattern (3+ occurrences): promote to scorecard, policy, or playbook.
If broadly applicable: consider skill extraction.
</supply-chain-self-improvement-reminder>
EOF


path: scripts/extract-skill.sh
content: #!/bin/bash
# Supply Chain Skill Extraction Helper
# Creates a new skill from a supply chain learning entry
# Usage: ./extract-skill.sh <skill-name> [--dry-run]

set -e

SKILLS_DIR="./skills"

RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m'

usage() {
    cat << EOF
Usage: $(basename "$0") <skill-name> [options]

Create a new supply chain skill from a learning entry.

Arguments:
  skill-name     Name of the skill (lowercase, hyphens for spaces)

Options:
  --dry-run      Show what would be created without creating files
  --output-dir   Relative output directory under current path (default: ./skills)
  -h, --help     Show this help message

Examples:
  $(basename "$0") safety-stock-optimization
  $(basename "$0") supplier-diversification-checklist --dry-run
  $(basename "$0") ocean-freight-contingency --output-dir ./skills/supply-chain

The skill will be created in: \$SKILLS_DIR/<skill-name>/
EOF
}

log_info() {
    echo -e "${GREEN}[INFO]${NC} $1"
}

log_warn() {
    echo -e "${YELLOW}[WARN]${NC} $1"
}

log_error() {
    echo -e "${RED}[ERROR]${NC} $1" >&2
}

SKILL_NAME=""
DRY_RUN=false

while [[ $# -gt 0 ]]; do
    case $1 in
        --dry-run)
            DRY_RUN=true
            shift
            ;;
        --output-dir)
            if [ -z "${2:-}" ] || [[ "${2:-}" == -* ]]; then
                log_error "--output-dir requires a relative path argument"
                usage
                exit 1
            fi
            SKILLS_DIR="$2"
            shift 2
            ;;
        -h|--help)
            usage
            exit 0
            ;;
        -*)
            log_error "Unknown option: $1"
            usage
            exit 1
            ;;
        *)
            if [ -z "$SKILL_NAME" ]; then
                SKILL_NAME="$1"
            else
                log_error "Unexpected argument: $1"
                usage
                exit 1
            fi
            shift
            ;;
    esac
done

if [ -z "$SKILL_NAME" ]; then
    log_error "Skill name is required"
    usage
    exit 1
fi

if ! [[ "$SKILL_NAME" =~ ^[a-z0-9]+(-[a-z0-9]+)*$ ]]; then
    log_error "Invalid skill name format. Use lowercase letters, numbers, and hyphens only."
    log_error "Examples: 'safety-stock-optimization', 'supplier-diversification', 'ocean-freight-contingency'"
    exit 1
fi

if [[ "$SKILLS_DIR" = /* ]]; then
    log_error "Output directory must be a relative path under the current directory."
    exit 1
fi

if [[ "$SKILLS_DIR" =~ (^|/)\.\.(/|$) ]]; then
    log_error "Output directory cannot include '..' path segments."
    exit 1
fi

SKILLS_DIR="${SKILLS_DIR#./}"
SKILLS_DIR="./$SKILLS_DIR"

SKILL_PATH="$SKILLS_DIR/$SKILL_NAME"

if [ -d "$SKILL_PATH" ] && [ "$DRY_RUN" = false ]; then
    log_error "Skill already exists: $SKILL_PATH"
    log_error "Use a different name or remove the existing skill first."
    exit 1
fi

if [ "$DRY_RUN" = true ]; then
    log_info "Dry run - would create:"
    echo "  $SKILL_PATH/"
    echo "  $SKILL_PATH/SKILL.md"
    echo ""
    echo "Template content would be:"
    echo "---"
    cat << TEMPLATE
name: $SKILL_NAME
description: "[TODO: Describe the supply chain pattern, risk mitigation, or operational improvement this skill addresses]"
---

# $(echo "$SKILL_NAME" | sed 's/-/ /g' | awk '{for(i=1;i<=NF;i++) $i=toupper(substr($i,1,1)) tolower(substr($i,2))}1')

[TODO: Brief introduction — what supply chain problem this solves]

## Quick Reference

| Situation | Action |
|-----------|--------|
| [Supply chain trigger] | [Mitigation or process to apply] |

## The Problem

[TODO: Describe the supply chain scenario — demand pattern, supplier behavior,
logistics constraint, or inventory condition that leads to the issue]

## Solution

[TODO: Step-by-step corrective and preventive actions]

## Key Metrics

| Metric | Target | Threshold |
|--------|--------|-----------|
| [KPI] | [Target] | [Alert level] |

## Prevention

[TODO: Policy change, monitoring threshold, escalation path]

## Source

- Learning ID: [TODO: Add original learning ID]
- Category: [TODO: forecast_error | supplier_risk | logistics_delay | inventory_mismatch | quality_deviation | demand_signal_shift]
- Area: [TODO: procurement | inventory | logistics | manufacturing | quality | demand_planning | warehousing]
- Original File: .learnings/LEARNINGS.md or .learnings/SUPPLY_CHAIN_ISSUES.md
TEMPLATE
    echo "---"
    exit 0
fi

log_info "Creating supply chain skill: $SKILL_NAME"

mkdir -p "$SKILL_PATH"

cat > "$SKILL_PATH/SKILL.md" << TEMPLATE
---
name: $SKILL_NAME
description: "[TODO: Describe the supply chain pattern, risk mitigation, or operational improvement this skill addresses]"
---

# $(echo "$SKILL_NAME" | sed 's/-/ /g' | awk '{for(i=1;i<=NF;i++) $i=toupper(substr($i,1,1)) tolower(substr($i,2))}1')

[TODO: Brief introduction — what supply chain problem this solves]

## Quick Reference

| Situation | Action |
|-----------|--------|
| [Supply chain trigger] | [Mitigation or process to apply] |

## The Problem

[TODO: Describe the supply chain scenario — demand pattern, supplier behavior,
logistics constraint, or inventory condition that leads to the issue]

## Solution

[TODO: Step-by-step corrective and preventive actions]

## Key Metrics

| Metric | Target | Threshold |
|--------|--------|-----------|
| [KPI] | [Target] | [Alert level] |

## Prevention

[TODO: Policy change, monitoring threshold, escalation path]

## Source

- Learning ID: [TODO: Add original learning ID]
- Category: [TODO: forecast_error | supplier_risk | logistics_delay | inventory_mismatch | quality_deviation | demand_signal_shift]
- Area: [TODO: procurement | inventory | logistics | manufacturing | quality | demand_planning | warehousing]
- Original File: .learnings/LEARNINGS.md or .learnings/SUPPLY_CHAIN_ISSUES.md
TEMPLATE

log_info "Created: $SKILL_PATH/SKILL.md"

echo ""
log_info "Skill scaffold created."
echo ""
echo "Next steps:"
echo "  1. Edit $SKILL_PATH/SKILL.md"
echo "  2. Fill in the TODO sections with supply chain specifics from your learning"
echo "  3. Add key metrics section (KPIs, targets, alert thresholds)"
echo "  4. Add prevention section (policy, monitoring, escalation)"
echo "  5. Add references/ folder if you have detailed documentation"
echo "  6. Update the original learning entry with:"
echo "     **Status**: promoted_to_skill"
echo "     **Skill-Path**: skills/$SKILL_NAME"


path: scripts/error-detector.sh
content: #!/bin/bash
# Supply Chain Self-Improvement Error Detector Hook (Optional)
# Detects operational disruption terms in PostToolUse output.
# Reads CLAUDE_TOOL_OUTPUT only when provided by the hook context.

set -e

OUTPUT="${CLAUDE_TOOL_OUTPUT:-}"

# If hook context didn't provide output, do nothing.
[ -n "$OUTPUT" ] || exit 0

ERROR_PATTERNS=(
    "stockout"
    "backorder"
    "delay"
    "shortage"
    "defect"
    "rejection"
    "recall"
    "overstock"
    "expired"
    "lead time"
    "capacity"
    "forecast"
    "variance"
    "disruption"
    "out of stock"
    "back order"
    "stock-out"
    "safety stock"
    "reorder point"
    "fill rate"
    "on-time delivery"
    "quality hold"
    "inspection fail"
    "shipping delay"
    "port congestion"
    "customs hold"
    "freight"
    "demurrage"
    "detention"
    "mismatch"
    "shrinkage"
    "cycle count"
    "inventory variance"
    "supplier fail"
    "MAPE"
    "understock"
    "allocation"
    "constraint"
    "bottleneck"
)

contains_error=false
for pattern in "${ERROR_PATTERNS[@]}"; do
    if [[ "$OUTPUT" == *"$pattern"* ]]; then
        contains_error=true
        break
    fi
done

if [ "$contains_error" = true ]; then
    cat << 'EOF'
<supply-chain-disruption-detected>
A supply chain issue was detected in command output. Consider logging to .learnings/ if:
- Stockout or backorder requires investigation → SUPPLY_CHAIN_ISSUES.md [SCM-YYYYMMDD-XXX]
- Delivery delay with non-obvious root cause → SUPPLY_CHAIN_ISSUES.md (logistics_delay)
- Supplier issue signals risk pattern → LEARNINGS.md (supplier_risk)
- Quality rejection above threshold → SUPPLY_CHAIN_ISSUES.md (quality_deviation)
- Forecast variance reveals model gap → LEARNINGS.md (forecast_error)
- Demand shift not captured by planning → LEARNINGS.md (demand_signal_shift)

Include impact metrics (units, cost, days affected). Specify area tag.
This reminder is documentation-only and does not execute any procurement or purchasing action.
</supply-chain-disruption-detected>
EOF
fi


path: hooks/openclaw/handler.js
content: /**
 * Self-Improving Supply Chain Hook for OpenClaw
 *
 * Injects a supply chain-specific reminder to evaluate learnings during agent bootstrap.
 * Fires on agent:bootstrap event before workspace files are injected.
 */

const REMINDER_CONTENT = `
## Supply Chain Self-Improvement Reminder

After completing supply chain tasks, evaluate if any learnings should be captured:

**Log supply chain issues when:**
- Stockout or backorder event detected → \`.learnings/SUPPLY_CHAIN_ISSUES.md\` (inventory_mismatch)
- Delivery SLA missed or shipment delayed → \`.learnings/SUPPLY_CHAIN_ISSUES.md\` (logistics_delay)
- Quality rejection or defect rate spike → \`.learnings/SUPPLY_CHAIN_ISSUES.md\` (quality_deviation)
- Warehouse at or above 90% capacity → \`.learnings/SUPPLY_CHAIN_ISSUES.md\` (inventory_mismatch)

**Log learnings when:**
- Forecast miss exceeds 15% MAPE → \`.learnings/LEARNINGS.md\` (forecast_error)
- Supplier lead time increased or supplier failed → \`.learnings/LEARNINGS.md\` (supplier_risk)
- Unexpected demand spike or channel shift → \`.learnings/LEARNINGS.md\` (demand_signal_shift)
- Routing inefficiency or logistics optimization found → \`.learnings/LEARNINGS.md\` (logistics_delay)

**Log feature requests when:**
- Supply chain tool or automation needed → \`.learnings/FEATURE_REQUESTS.md\`

**Promote when pattern is proven (3+ occurrences):**
- Supplier patterns → supplier scorecards
- Inventory patterns → safety stock policies
- Routing patterns → routing playbooks
- Forecast patterns → demand planning models
- Quality patterns → quality acceptance criteria

Include impact metrics (units, cost, days). Specify area tag.
`.trim();

const handler = async (event) => {
  if (!event || typeof event !== 'object') {
    return;
  }

  if (event.type !== 'agent' || event.action !== 'bootstrap') {
    return;
  }

  if (!event.context || typeof event.context !== 'object') {
    return;
  }

  if (Array.isArray(event.context.bootstrapFiles)) {
    event.context.bootstrapFiles.push({
      path: 'SUPPLY_CHAIN_SELF_IMPROVEMENT_REMINDER.md',
      content: REMINDER_CONTENT,
      virtual: true,
    });
  }
};

module.exports = handler;
module.exports.default = handler;


path: hooks/openclaw/HOOK.md
content: ---
name: self-improving-supply-chain
description: "Injects supply chain self-improvement reminder during agent bootstrap"
metadata: {"openclaw":{"emoji":"📦","events":["agent:bootstrap"]}}
---

# Self-Improving Supply Chain Hook

Injects a reminder to evaluate supply chain learnings during agent bootstrap.

## What It Does

- Fires on `agent:bootstrap` (before workspace files are injected)
- Adds a supply chain-specific reminder block to check `.learnings/` for relevant entries
- Prompts the agent to log stockouts, delivery delays, supplier failures, quality rejections, forecast misses, demand signal shifts, and capacity breaches
- Reminder-only behavior: does not place orders, execute purchases, or call external payment/commerce services

## Reminder Content

The hook injects reminders to log to the appropriate file based on what occurred:

| Trigger | Target File | Category |
|---------|-------------|----------|
| Stockout or backorder event | `SUPPLY_CHAIN_ISSUES.md` | `inventory_mismatch` |
| Delivery SLA miss or delay | `SUPPLY_CHAIN_ISSUES.md` | `logistics_delay` |
| Supplier lead time increase | `LEARNINGS.md` | `supplier_risk` |
| Quality rejection or defect | `SUPPLY_CHAIN_ISSUES.md` | `quality_deviation` |
| Forecast MAPE >15% | `LEARNINGS.md` | `forecast_error` |
| Demand spike or shift | `LEARNINGS.md` | `demand_signal_shift` |
| Warehouse capacity >90% | `SUPPLY_CHAIN_ISSUES.md` | `inventory_mismatch` |

## Configuration

No configuration needed. Enable with:

```bash
openclaw hooks enable self-improving-supply-chain
```


path: hooks/openclaw/handler.ts
content: /**
 * Self-Improving Supply Chain Hook for OpenClaw
 *
 * Injects a supply chain-specific reminder to evaluate learnings during agent bootstrap.
 * Fires on agent:bootstrap event before workspace files are injected.
 */

import type { HookHandler } from 'openclaw/hooks';

const REMINDER_CONTENT = `## Supply Chain Self-Improvement Reminder

After completing supply chain tasks, evaluate if any learnings should be captured:

**Log supply chain issues when:**
- Stockout or backorder event detected → \`.learnings/SUPPLY_CHAIN_ISSUES.md\` (inventory_mismatch)
- Delivery SLA missed or shipment delayed → \`.learnings/SUPPLY_CHAIN_ISSUES.md\` (logistics_delay)
- Quality rejection or defect rate spike → \`.learnings/SUPPLY_CHAIN_ISSUES.md\` (quality_deviation)
- Warehouse at or above 90% capacity → \`.learnings/SUPPLY_CHAIN_ISSUES.md\` (inventory_mismatch)

**Log learnings when:**
- Forecast miss exceeds 15% MAPE → \`.learnings/LEARNINGS.md\` (forecast_error)
- Supplier lead time increased or supplier failed → \`.learnings/LEARNINGS.md\` (supplier_risk)
- Unexpected demand spike or channel shift → \`.learnings/LEARNINGS.md\` (demand_signal_shift)
- Routing inefficiency or logistics optimization found → \`.learnings/LEARNINGS.md\` (logistics_delay)

**Log feature requests when:**
- Supply chain tool or automation needed → \`.learnings/FEATURE_REQUESTS.md\`

**Promote when pattern is proven (3+ occurrences):**
- Supplier patterns → supplier scorecards
- Inventory patterns → safety stock policies
- Routing patterns → routing playbooks
- Forecast patterns → demand planning models
- Quality patterns → quality acceptance criteria

Include impact metrics (units, cost, days). Specify area tag.`;

const handler: HookHandler = async (event) => {
  if (!event || typeof event !== 'object') {
    return;
  }

  if (event.type !== 'agent' || event.action !== 'bootstrap') {
    return;
  }

  if (!event.context || typeof event.context !== 'object') {
    return;
  }

  const sessionKey = event.sessionKey || '';
  if (sessionKey.includes(':subagent:')) {
    return;
  }

  if (Array.isArray(event.context.bootstrapFiles)) {
    event.context.bootstrapFiles.push({
      path: 'SUPPLY_CHAIN_SELF_IMPROVEMENT_REMINDER.md',
      content: REMINDER_CONTENT,
      virtual: true,
    });
  }
};

export default handler;


path: references/openclaw-integration.md
content: # OpenClaw Integration

Complete setup and usage guide for integrating the self-improving-supply-chain skill with OpenClaw.

## Overview

OpenClaw uses workspace-based prompt injection combined with event-driven hooks. Context is injected from workspace files at session start, and hooks can trigger on lifecycle events.

## Workspace Structure

```
~/.openclaw/
├── workspace/                   # Working directory
│   ├── AGENTS.md               # Multi-agent coordination patterns
│   ├── SOUL.md                 # Behavioral guidelines and personality
│   ├── TOOLS.md                # Tool capabilities and gotchas
│   ├── MEMORY.md               # Long-term memory (main session only)
│   └── memory/                 # Daily memory files
│       └── YYYY-MM-DD.md
├── skills/                      # Installed skills
│   └── self-improving-supply-chain/
│       └── SKILL.md
└── hooks/                       # Custom hooks
    └── self-improving-supply-chain/
        ├── HOOK.md
        └── handler.ts
```

## Quick Setup

### 1. Install the Skill

```bash
clawdhub install self-improving-supply-chain
```

Or copy manually:

```bash
cp -r self-improving-supply-chain ~/.openclaw/skills/
```

### 2. Install the Hook (Optional)

```bash
cp -r hooks/openclaw ~/.openclaw/hooks/self-improving-supply-chain
openclaw hooks enable self-improving-supply-chain
```

### 3. Create Learning Files

```bash
mkdir -p ~/.openclaw/workspace/.learnings
```

## Promotion Targets (Supply Chain-Specific)

When supply chain learnings prove broadly applicable, promote them to operational standards:

| Learning Type | Promote To | Example |
|---------------|------------|---------|
| Supplier performance patterns | Supplier scorecards | "Require dual-source for components >$50K annual spend" |
| Inventory buffer patterns | Safety stock policies | "Ocean-freight SKUs carry 3 weeks safety stock" |
| Routing optimizations | Routing playbooks | "Divert to Nansha port when Yantian queue >5 days" |
| Forecast accuracy patterns | Demand planning models | "Apply seasonal index for gift-category SKUs in Q4" |
| Quality failure patterns | Quality acceptance criteria | "Inspect 100% of first shipment from new suppliers" |
| Workflow improvements | `AGENTS.md` | "Run inventory reconciliation before reorder point calc" |

### Promotion Decision Tree

```
Is the learning project-specific?
├── Yes → Keep in .learnings/
└── No → Is it a supplier performance pattern?
    ├── Yes → Promote to supplier scorecard
    └── No → Is it an inventory/stock pattern?
        ├── Yes → Promote to safety stock policy
        └── No → Is it a logistics/routing pattern?
            ├── Yes → Promote to routing playbook
            └── No → Is it a forecast/demand pattern?
                ├── Yes → Promote to demand planning model
                └── No → Promote to TOOLS.md or AGENTS.md
```

## Supply Chain-Specific Detection Triggers

| Trigger | Action | Target |
|---------|--------|--------|
| Stockout or backorder event | Log supply chain issue | SUPPLY_CHAIN_ISSUES.md (inventory_mismatch) |
| Delivery SLA miss | Log supply chain issue | SUPPLY_CHAIN_ISSUES.md (logistics_delay) |
| Quality rejection spike | Log supply chain issue | SUPPLY_CHAIN_ISSUES.md (quality_deviation) |
| Supplier lead time increase | Log learning | LEARNINGS.md (supplier_risk) |
| Forecast MAPE >15% | Log learning | LEARNINGS.md (forecast_error) |
| Demand signal shift | Log learning | LEARNINGS.md (demand_signal_shift) |
| Warehouse capacity >90% | Log supply chain issue | SUPPLY_CHAIN_ISSUES.md (inventory_mismatch) |

## Inter-Agent Communication

OpenClaw provides tools for cross-session communication. Use only when cross-session sharing is explicitly needed.

### sessions_send

Share a supply chain insight with another session:
```
sessions_send(sessionKey="session-id", message="Supplier risk: SMT-4421 lead time increased 75%, begin alternate qualification immediately")
```

### sessions_spawn

Spawn a background agent to analyze supply chain patterns:
```
sessions_spawn(task="Analyze .learnings/SUPPLY_CHAIN_ISSUES.md for recurring delay patterns and promotion candidates", label="scm-review")
```

## Available Hook Events

| Event | When It Fires |
|-------|---------------|
| `agent:bootstrap` | Before workspace files inject |
| `command:new` | When `/new` command issued |
| `command:reset` | When `/reset` command issued |
| `command:stop` | When `/stop` command issued |
| `gateway:startup` | When gateway starts |

## Verification

```bash
openclaw hooks list        # Check hook is registered
openclaw status            # Check skill is loaded
```

## Troubleshooting

### Hook not firing
1. Ensure hooks enabled in config
2. Restart gateway after config changes
3. Check gateway logs for errors

### Learnings not persisting
1. Verify `.learnings/` directory exists
2. Check file permissions
3. Ensure workspace path is configured correctly

### Skill not loading
1. Check skill is in skills directory
2. Verify SKILL.md has correct frontmatter
3. Run `openclaw status` to see loaded skills


path: references/hooks-setup.md
content: # Hook Setup Guide

Configure automatic supply chain self-improvement triggers for AI agents.

## Overview

Hooks enable proactive supply chain pattern capture by injecting reminders at key moments:
- **UserPromptSubmit**: Reminder after each prompt to evaluate supply chain learnings
- **PostToolUse (Bash)**: Error detection when supply chain commands reveal disruptions, stockouts, or delays

## Claude Code Setup

### Option 1: Project-Level Configuration

Create `.claude/settings.json` in your project root:

```json
{
  "hooks": {
    "UserPromptSubmit": [
      {
        "matcher": "",
        "hooks": [
          {
            "type": "command",
            "command": "./skills/self-improving-supply-chain/scripts/activator.sh"
          }
        ]
      }
    ],
    "PostToolUse": [
      {
        "matcher": "Bash",
        "hooks": [
          {
            "type": "command",
            "command": "./skills/self-improving-supply-chain/scripts/error-detector.sh"
          }
        ]
      }
    ]
  }
}
```

### Option 2: User-Level Configuration

Add to `~/.claude/settings.json` for global activation:

```json
{
  "hooks": {
    "UserPromptSubmit": [
      {
        "matcher": "",
        "hooks": [
          {
            "type": "command",
            "command": "~/.claude/skills/self-improving-supply-chain/scripts/activator.sh"
          }
        ]
      }
    ]
  }
}
```

### Minimal Setup (Activator Only)

For lower overhead, use only the UserPromptSubmit hook:

```json
{
  "hooks": {
    "UserPromptSubmit": [
      {
        "matcher": "",
        "hooks": [
          {
            "type": "command",
            "command": "./skills/self-improving-supply-chain/scripts/activator.sh"
          }
        ]
      }
    ]
  }
}
```

## Codex CLI Setup

Codex uses the same hook system. Create `.codex/settings.json`:

```json
{
  "hooks": {
    "UserPromptSubmit": [
      {
        "matcher": "",
        "hooks": [
          {
            "type": "command",
            "command": "./skills/self-improving-supply-chain/scripts/activator.sh"
          }
        ]
      }
    ]
  }
}
```

## GitHub Copilot Setup

Copilot doesn't support hooks. Add guidance to `.github/copilot-instructions.md`:

```markdown
## Supply Chain Self-Improvement

After resolving supply chain issues, consider logging to `.learnings/`:
- Stockouts, delays, quality problems → SUPPLY_CHAIN_ISSUES.md
- Forecast misses, supplier risks, demand shifts → LEARNINGS.md
- Tool/capability requests → FEATURE_REQUESTS.md

Promote recurring patterns to supplier scorecards, safety stock policies, or routing playbooks.
```

## Verification

### Test Activator Hook

1. Enable the hook configuration
2. Start a new Claude Code session
3. Send any prompt
4. Verify you see `<supply-chain-self-improvement-reminder>` in the context

### Test Error Detector Hook

1. Enable PostToolUse hook for Bash
2. Run a command that produces supply chain output with keywords like "stockout" or "backorder"
3. Verify you see `<supply-chain-disruption-detected>` reminder

### Dry Run Extract Script

```bash
./skills/self-improving-supply-chain/scripts/extract-skill.sh safety-stock-optimization --dry-run
```

## Troubleshooting

### Hook Not Triggering

1. **Check script permissions**: `chmod +x scripts/*.sh`
2. **Verify path**: Use absolute paths or paths relative to project root
3. **Check settings location**: Project vs user-level settings
4. **Restart session**: Hooks are loaded at session start

### Permission Denied

```bash
chmod +x ./skills/self-improving-supply-chain/scripts/activator.sh
chmod +x ./skills/self-improving-supply-chain/scripts/error-detector.sh
chmod +x ./skills/self-improving-supply-chain/scripts/extract-skill.sh
```

### Script Not Found

If using relative paths, ensure you're in the correct directory or use absolute paths:

```json
{
  "command": "/absolute/path/to/skills/self-improving-supply-chain/scripts/activator.sh"
}
```

### Too Much Overhead

If the activator feels intrusive:

1. **Use minimal setup**: Only UserPromptSubmit, skip PostToolUse
2. **Add matcher filter**: Only trigger for supply chain-related prompts:

```json
{
  "matcher": "inventory|supplier|forecast|shipment|warehouse|procurement|logistics",
  "hooks": [...]
}
```

## Hook Output Budget

The activator is designed to be lightweight:
- **Target**: ~50-100 tokens per activation
- **Content**: Structured supply chain-specific reminder, not verbose instructions
- **Format**: XML tags for easy parsing

## Security Considerations

- Hook scripts run with the same permissions as the agent
- Scripts only output text; they don't modify files or run commands
- Error detector reads `CLAUDE_TOOL_OUTPUT` environment variable
- Treat `CLAUDE_TOOL_OUTPUT` as potentially sensitive; do not log verbatim
- All scripts are opt-in
- Recommended default: enable `UserPromptSubmit` only; add `PostToolUse` when you want supply chain disruption detection
- No credentials, payment tokens, or procurement transaction permissions are required by this skill
- This skill does not place orders, execute purchases, or call external commerce APIs

## Disabling Hooks

To temporarily disable without removing configuration:

1. Comment out in settings
2. Or delete the settings file — hooks won't run without configuration


Security scan verdicts — ClawScan: clean | static analysis: clean | VirusTotal: clean | SkillSpector: suspicious (CRITICAL)