Skill: dakshhmehta/smart-accountant (version 1.0.0)

# Accountant Agent Skill Mastery Guide Welcome to the Accountant Agent Skill repository! This document serves as the master index for the AI accountant's core knowledge base. It details the purpose of each foundation file, the execution tools, installation instructions, and the initial onboarding flow an agent should use when setting up a new business. --- ## 📚 Core Knowledge Base Files ### 1. `audit_rule.md` - **What it is for:** Defines preventive, detective, and corrective audit controls. - **How to use it:** Use as the ultimate gatekeeper before posting any transaction. Enforces the "Maker-Checker" protocol where the agent drafts and the human confirms. - **What it contains:** Three layers of controls, Golden Audit Checks, anomaly detection, and validation requirements (e.g., preventing unbalanced journals). - **Why it's important:** Prevents financial data corruption, fraud, and ensures mathematical accuracy before any database write occurs. ### 2. `closing.md` - **What it is for:** Defines the operational workflows for period-end closures (Monthly, Quarterly, and Yearly). - **How to use it:** Use to guide the agent through reconciliation checklists before locking a financial period. - **What it contains:** Step-by-step procedures for capturing, reconciling, adjusting, reviewing, reporting, and locking. Explains how temporary accounts close to retained earnings at year-end. - **Why it's important:** Certifies financial truth for a given period and legally locks historical records to prevent backdated manipulations. ### 3. `coa.md` (Chart of Accounts) - **What it is for:** The foundational classification system for all financial buckets. - **How to use it:** Use to classify every ledger into one of the 5 primary types: Assets, Liabilities, Equity, Income, or Expenses. - **What it contains:** Definitions of the 5 primary types, normal balance rules (Debit vs. Credit), and the foundational accounting equation (Assets = Liabilities + Equity). - **Why it's important:** Proper classification dictates how transactions behave and how financial reports are ultimately structured. ### 4. `db.md` & `db_tool.md` - **What it is for:** Defines the architectural bridge between accounting theory and the actual `better-sqlite3` execution engine. - **How to use it:** Guides the agent on how to call specific `scripts/` (syscalls) rather than improvising raw SQL. - **What it contains:** The architecture of the `tool/` directory, schema definitions, transactional requirements (WAL mode), and detailed instructions on how the posting engine works. - **Why it's important:** Ensures deterministic, low-tool-call operations that safely persist financial data in an ACID-compliant database. ### 5. `general_ledger.md` - **What it is for:** Explains the hierarchy of Ledgers and Ledger Groups. - **How to use it:** Use to understand how journal entries accumulate into running balances over time. - **What it contains:** The distinction between postable ledgers (where transactions happen) and non-postable ledger groups (used only for organization). - **Why it's important:** Prevents the agent from accidentally posting transactions to summary folders, ensuring granular transaction tracking. ### 6. `journal_entry.md` - **What it is for:** Teaches the agent how to translate business events into formal double-entry accounting records. - **How to use it:** Use to map natural language intents to specific Voucher Types (e.g., CR, BP, SE, PE) and apply Debit/Credit logic. - **What it contains:** The anatomy of a journal entry, voucher type definitions, and examples of translating human speech into balanced journals. - **Why it's important:** It guarantees that every financial event adheres to the fundamental rule: Total Debits must equal Total Credits. ### 7. `rectification.md` - **What it is for:** Transaction correction logic for handling mistakes. - **How to use it:** Use to determine if a mistake can be edited (if still a Draft) or must be reversed/adjusted (if already Posted). - **What it contains:** Rules for reversing vouchers, adjusting entries, and enforcing the two-stage posting model (Draft -> Preview -> Confirm -> Post). - **Why it's important:** Enforces an append-only, immutable audit trail. History is never silently overwritten. ### 8. `report_manual.md` - **What it is for:** Defines the output reporting layer of the accounting system. - **How to use it:** Use to generate the 12 core reports (Trial Balance, P&L, Balance Sheet, Cash Flow, etc.) dynamically from the ledger. - **What it contains:** Definitions, generation logic, and example layouts for every critical financial report. - **Why it's important:** Provides the human owner with visibility into the financial health, liquidity, and profitability of the business. ### 9. `source_document.md` - **What it is for:** Defines the required evidence that must exist before a transaction is recorded. - **How to use it:** Use to map physical/digital documents (Invoices, Receipts, Bank Statements) to system Voucher Types. - **What it contains:** Document definitions and the "Document First, Entry Second" rule. - **Why it's important:** Ensures that the agent does not fabricate entries without underlying business proof. ### 10. `transaction_language.md` - **What it is for:** NLP keyword mappings. - **How to use it:** Use as a dictionary to parse user intent and colloquials into formal accounting commands. - **What it contains:** Extensive lists of keywords, phrases, and Indian/Global colloquialisms mapped to specific voucher types. - **Why it's important:** Enables seamless, conversational human-agent interaction without requiring the user to speak in strict accounting terms. --- ## 🛠 Installation & Setup The actual execution logic resides in the `tool/` directory, powered by Node.js and `better-sqlite3`. To set up the database and toolset: ```bash # 1. Navigate to the tool directory cd tool/ # 2. Install dependencies (better-sqlite3) npm install # 3. Initialize the database schema (Creates accounting.db) node scripts/migrate-schema.js # 4. Verify database integrity node scripts/integrity-check.js ``` Once initialized, the system uses the scripts in `tool/scripts/` (e.g., `post-voucher.js`, `generate-report.js`) as the primary interface for all ledger operations. --- ## 🤝 Initial Onboarding: Accountant Initialization Interview When the Accountant Agent is installed or attached to a new workspace, it should behave like a professional human accountant onboarding a new client. Before recording any daily transactions, the agent MUST ask the user the following questions to properly initialize the books: 1. **Business Entity & Reporting Period:** > "What is the legal name of the business, and what is your financial year (e.g., April to March or Jan to Dec)?" 2. **Opening Balances (The Transition):** > "Are we starting fresh, or do you have an existing Trial Balance / Balance Sheet from a previous system that we need to import as opening balances?" 3. **Cash & Banks:** > "What are your primary bank accounts and cash registers? We need to set these up as your core Asset ledgers." 4. **Chart of Accounts (COA) Customization:** > "Do you have specific expense/income categories you want to track granularly, or should I initialize a standard Chart of Accounts for your industry?" 5. **Initial Capital (For New Businesses):** > "If this is a brand new business, how much initial owner's capital has been introduced, and into which bank or cash account was it deposited?" 6. **Outstanding Dues (Day One AR/AP):** > "Are there any pending payables to suppliers or receivables from customers that we need to record on day one to ensure accurate cash flow tracking?" Once these questions are answered, the agent will use the `tool/` scripts to generate the Opening Entries (`OE`) and establish the initial Trial Balance.

path: gst_posting_workflow.md
content: # GST Posting Workflow
Version: 1.0
Layer: Workflow Skill

Purpose:
Define mandatory posting sequence.

---

## Workflow

Step 1
Read source document.

Extract:
- Party
- Taxable value
- Rate
- Supply type
- Place of supply
- GST relevance

---

Step 2
Resolve party tax treatment.

---

Step 3
Run GST applicability checks.

Questions:

- GST applicable?
- Exempt?
- Reverse charge?
- ITC eligible?
- Missing GST risk?

---

Step 4
Generate proposed tax lines.

Auto build journal.

---

Step 5
Run Missed GST rules.

Check all detection triggers.

---

Step 6
Show posting preview.

Display:

Tax Preview
Journal Preview
Risk Flags

Example:

Purchases Dr ...
Input CGST Dr ...
Input SGST Dr ...
To Vendor ...

---

Step 7
Require user confirmation.

Only then:

Commit posting.

---

## Workflow Pseudocode

on_transaction():

validate_source()

resolve_tax()

build_tax_entry()

run_missed_gst_detection()

preview()

if user_confirms:
 post()
else:
 stop()

---

## Forbidden Workflow

Never:

Receive invoice
→ post immediately
→ fix GST later

Forbidden.

---

## Exception Handling

Rectification entries:
Allowed only through review.

Never bypass workflow.

---

## Skill Interaction Priority

Workflow order:

gst_guard
then
missed_gst_rules
then
posting

Not reverse.

---

## Golden Rule

No GST-sensitive transaction posts
without:
- determination
- validation
- preview
- approval

path: transaction_language.md
content: # transaction_language.md

## Purpose
This file defines natural language variations used by humans when referring to accounting transactions.
It helps the agent map user intent → correct voucher type.

---

# 1. SALES INVOICE (SE - Sales Entry)

## Keywords
sales invoice, customer invoice, tax invoice, sales bill, outward invoice, revenue invoice

## Examples
- Create a sales invoice for ₹25,000 to ABC Traders
- Raise an invoice for the goods sold yesterday
- Enter this customer bill as a sales entry
- Post an outward tax invoice for this sale
- Record invoice no SI-1045 for customer payment
- Make a sales bill for 100 bags supplied
- Book revenue against this invoice
- Pass a sales voucher for this order
- Generate an output invoice with GST
- Record a credit sale invoice

---

# 2. PURCHASE INVOICE (PE - Purchase Entry)

## Keywords
purchase bill, supplier invoice, vendor bill, input invoice, inward bill

## Examples
- Enter supplier invoice from Reliance Chemicals
- Record this purchase bill for raw materials
- Post a vendor invoice worth ₹48,000
- Make a purchase entry against invoice no 4567
- Book this inward invoice under purchases
- Record GST input purchase from this bill
- Pass purchase voucher for chemicals bought
- Enter vendor bill received on credit
- Post invoice received from supplier
- Add this bill into purchase register

---

# 3. CASH RECEIPT (CR)

## Keywords
cash received, cash collection, receipt voucher, money received

## Examples
- Record cash received from customer
- Pass a cash receipt for ₹15,000
- Enter receipt voucher for cash payment
- Book cash collection from debtor
- Record cash received toward dues
- Post customer cash payment
- Make CR voucher for rent received
- Enter money received in hand
- Record walk-in customer cash receipt
- Pass receipt entry for cash deposit

---

# 4. BANK RECEIPT (BR)

## Keywords
bank receipt, NEFT received, RTGS received, bank credit, transfer received

## Examples
- Record bank receipt from customer via NEFT
- Post amount received in bank
- Enter BR for ₹50,000 received by RTGS
- Book payment received through bank transfer
- Record customer payment credited in bank
- Pass receipt for cheque realized
- Enter UPI receipt in bank account
- Record wire transfer from client
- Book incoming bank payment
- Make bank receipt entry

---

# 5. CASH PAYMENT (CP)

## Keywords
cash paid, petty cash, cash expense, cash disbursement

## Examples
- Record cash paid for office expenses
- Pass cash payment for transport charges
- Enter petty cash payment of ₹2,000
- Book cash paid to supplier
- Record cash for labor wages
- Make CP voucher for electricity
- Post cash expense paid today
- Enter payment made in cash
- Record reimbursement from cash
- Pass cash settlement entry

---

# 6. BANK PAYMENT (BP)

## Keywords
bank payment, online payment, cheque payment, transfer made

## Examples
- Record bank payment to supplier by NEFT
- Pass BP voucher for vendor payment
- Enter online transfer for raw materials
- Book cheque issued to supplier
- Record bank payment of rent
- Make payment for utility bill via bank
- Post outgoing bank transfer
- Record UPI payment from account
- Enter wire payment to vendor
- Book supplier settlement through bank

---

# 7. SALES RETURN / CREDIT NOTE (SR)

## Keywords
credit note, sales return, customer return, credit memo

## Examples
- Issue credit note for returned goods
- Record sales return from customer
- Pass SR for damaged goods returned
- Enter customer return with adjustment
- Book credit note against invoice
- Reverse sale due to rejection
- Post return voucher
- Make credit memo for excess billing
- Record output return adjustment
- Pass sales return entry

---

# 8. PURCHASE RETURN / DEBIT NOTE (PR)

## Keywords
debit note, purchase return, supplier return

## Examples
- Record purchase return to supplier
- Raise debit note for defective material
- Pass PR voucher for goods returned
- Enter supplier return adjustment
- Book debit note against wrong supply
- Reverse purchase due to damage
- Record vendor return memo
- Post debit adjustment for shortage
- Make purchase return entry
- Pass debit note for rejected materials

---

# 9. CONTRA ENTRY (CN)

## Keywords
contra, cash to bank, bank to cash, internal transfer

## Examples
- Record cash deposited into bank
- Pass contra for bank withdrawal
- Transfer ₹20,000 from cash to bank
- Enter internal fund transfer
- Book cash withdrawn for expenses
- Make CN for bank transfer
- Record transfer between accounts
- Post ATM withdrawal entry
- Enter funds moved internally
- Pass internal transfer voucher

---

# 10. JOURNAL ENTRY (JE)

## Keywords
journal entry, adjustment entry, manual entry, accrual, provision

## Examples
- Pass journal entry for depreciation
- Record adjusting entry for expenses
- Make JE for salary provision
- Post manual journal for reclassification
- Enter adjustment for prepaid rent
- Book write-off entry
- Pass rectification entry
- Record month-end accrual
- Make provision for audit fees
- Post general journal adjustment

---

# 11. OPENING ENTRY (OE)

## Keywords
opening balance, opening entry, brought forward

## Examples
- Enter opening balances
- Pass opening entry for bank balance
- Record opening stock
- Create OE for debtor balances
- Book beginning balances
- Post opening capital
- Enter brought-forward balances
- Set up opening journal
- Record opening vendor balances
- Import opening trial balance

---

# 12. BANK STATEMENT DRIVEN ENTRIES (AUTO / MIXED)

## Keywords
bank reconciliation, statement entry, bank import

## Examples
- Reconcile bank statement transactions
- Record entries from bank statement
- Match this statement line
- Post bank charges from statement
- Book interest credited in bank
- Record cheque bounce
- Enter contra from bank deposit
- Pass journal for bank charges
- Record statement transactions
- Reconcile and create vouchers

---

# COMMON COLLOQUIAL PHRASES (IMPORTANT)

## Indian + Global Usage
- pass entry
- do voucher
- book this transaction
- post this bill
- make receipt
- adjust this
- reverse this entry
- knock off invoice
- settle payment
- journal karo
- contra maaro
- receipt book karo
- bill punch karo

---

# NOTES FOR AGENT

1. Always infer intent from action words:
   - "receive" → CR / BR
   - "pay" → CP / BP
   - "return" → SR / PR
   - "transfer" → CN
   - "adjust" → JE

2. If ambiguity exists:
   - Ask: cash or bank?
   - Ask: sale or purchase?

3. Prefer structured mapping:
   - Sales → SE / SR
   - Purchase → PE / PR
   - Money In → CR / BR
   - Money Out → CP / BP

4. Bank statement inputs may generate:
   - BR / BP / CN / JE depending on nature

---


path: gst_validation_example.md
content: # GST Validation Examples
Version: 1.0

Purpose:
Teach the agent examples of correct vs incorrect treatment.

---

## Example 1
Purchase Intrastate

Input:
Purchase 100000
GST 18%
Same state

Expected:

Purchases Dr 100000
Input CGST Dr 9000
Input SGST Dr 9000
To Vendor 118000

Pass

---

## Example 2
Wrong Gross Expense Booking

Input:

Repairs Expense Dr 118000
To Vendor 118000

Detect:
Missed input GST

Suggested:

Repairs Expense Dr 100000
Input GST Dr 18000
To Vendor 118000

Flag warning

---

## Example 3
Interstate Wrong Tax Split

Input:
Vendor state different
CGST booked

Flag:
Error

Correct:
Use IGST

---

## Example 4
Sales Without GST

Customer Dr 100000
To Sales 100000

Taxable supply.

Flag:
Output GST Missing

---

## Example 5
Manual JE touching GST

Input GST Dr ...
To Suspense

Force review.

---

## Example 6
RCM Incomplete

Only liability booked.

Flag:
Missing dual impact.

---

## Example 7
Missing GSTIN

Vendor invoice posted.
No GSTIN.

Prompt:
Registered vendor?
Unregistered?
RCM?

Do not assume.

---

## Example Rule

Examples act as reasoning patterns,
not rigid templates.
Use analogous reasoning.

path: db_tool.md
content: # db_tool.md
Version: 1.0
Purpose: AI-readable operational skill for database tooling, integrity controls, and exec-driven helper scripts using better-sqlite3 for 
accounting-grade agents.

---

# Skill Intent

This skill defines how an agent should use SQLite tooling safely, quickly, and deterministically.

This is NOT generic database guidance.

This is:

- execution layer discipline
- tool-call reduction layer
- data integrity layer
- accounting persistence layer
- reusable script syscall layer

Primary stack:

```text
SQLite
better-sqlite3
single .db file
exec tool
scripts/ syscall layer
```

Use this skill whenever the agent:

- posts transactions
- queries ledger data
- runs aggregates
- performs reconciliation
- validates integrity
- closes periods
- mutates accounting records
- needs high-trust persistence

---

# Core Principles

Every financial mutation must satisfy:

```text
1 Valid
2 Balanced
3 Atomic
4 Idempotent
5 Audited
6 Reversible
7 Append-only
```

Never violate these.

---

# Database Initialization Standard

Always initialize database with:

```javascript
db.pragma('journal_mode = WAL')
db.pragma('foreign_keys = ON')
db.pragma('synchronous = FULL')
db.pragma('busy_timeout = 5000')
db.pragma('temp_store = MEMORY')
```

Prefer:

```text
synchronous=FULL
```

for accounting safety.

---

# Golden Posting Rule

Never post directly from user intent.

Mandatory flow:

```text
User Intent
-> Parse
-> Draft
-> Validate
-> Preview
-> Confirm
-> Commit
-> Audit Log
```

Never:

```text
User intent
-> insert rows directly
```

Forbidden.

---

# Two-Phase Posting Rule

Use staged posting.

Statuses:

```text
DRAFT
VALIDATED
POSTED
REVERSED
```

Tables:

```sql
draft_entries
posted_entries
```

Workflow:

```text
create draft
validate draft
preview draft
confirm
promote to posted
```

---

# Double Entry Enforcement

Before posting:

must verify:

```text
Total Debit = Total Credit
```

Check:

```sql
SELECT
SUM(debit),
SUM(credit)
FROM draft_lines
WHERE voucher_id=?
```

If unequal:

```text
Abort immediately
```

Hard failure.

---

# Idempotency Rule

All postings require request_id.

Schema:

```sql
request_id TEXT UNIQUE
```

Before posting:

```sql
SELECT id
FROM vouchers
WHERE request_id=?
```

If exists:

```text
Return existing voucher.
Never repost.
```

Mandatory.

---

# Append-Only Ledger Rule

Never do:

```sql
UPDATE ledger ...
DELETE ledger ...
```

Never modify historical ledger rows.

Corrections happen only through:

```text
reverse
adjust
rectify
```

using new entries.

---

# Immutable Audit Trail

Maintain:

```sql
audit_log(
 id,
 event_type,
 entity_id,
 before_json,
 after_json,
 actor,
 timestamp
)
```

Every mutation writes audit event.

Append-only.

---

# Database Constraints Rule

Push integrity into schema.

Use:

```sql
NOT NULL
CHECK(...)
UNIQUE(...)
FOREIGN KEY(...)
```

Examples:

```sql
debit REAL CHECK(debit>=0),
credit REAL CHECK(credit>=0),
voucher_no TEXT UNIQUE
```

Do not rely only on model reasoning.

Database enforces truth.

---

# Savepoint Rule

For multi-step operations use:

```sql
SAVEPOINT post_tx
...
ROLLBACK TO post_tx
```

For partial recovery.

---

# Prepared Statement Registry

Do not dynamically build SQL repeatedly.

Use statement registry.

Example:

```javascript
statements={
 insertVoucher:...,
 insertLine:...,
 trialBalance:...
}
```

Reuse prepared statements.

Faster.
Safer.

---

# Exec Script Syscall Layer

Use scripts/ as database syscall layer.

Preferred structure:

```text
scripts/
 post-voucher.js
 preview-voucher.js
 reverse-voucher.js
 rectify-entry.js
 ledger-query.js
 generate-report.js
 reconcile.js
 integrity-check.js
 close-period.js
 db-maintenance.js
 migrate-schema.js

lib/
 db.js
 validators.js
 posting-engine.js
 interpreter.js
```

Scripts should be deterministic.

One script = one accounting verb.

---

# Script Definitions

==================================================
SCRIPT
post-voucher.js
==================================================

Primary write engine.

Invocation:

```bash
node scripts/post-voucher.js payload.json
```

Must enforce Maker-Checker protocol:
Do not run directly from user intent.
Requires valid voucher type (CR, BR, JE, etc.) and source document reference.

Performs:
- idempotency check
- final balance validation
- period open check
- voucher number generation
- transaction posting
- audit logging
- commit or rollback

Workflow:
```text
BEGIN
validate
insert voucher
insert lines
update derived balances
audit log
COMMIT
```

Rollback on failure. All writes flow through this engine.

---

# preview-voucher.js

Dry-run simulation and Audit Rule Enforcer.

Enforces:
- Completeness check
- Logic check
- Risk check
- Control check

Shows:
- proposed journal
- affected ledgers
- debit/credit totals
- warnings
- posting impact

No writes. Mandatory step before commit.

---

# reverse-voucher.js

Never edits originals.

Creates reversal entry.

Process:

- fetch original
- invert debits/credits
- post reversal
- link reversal voucher

Uses post-voucher engine internally.

---

# rectify-entry.js

Correction workflow:

```text
reverse incorrect entry
post corrected entry
```

Atomic.

Should call post-voucher engine.

---

# ledger-query.js

Universal read script.

Supports:

- account inquiry
- voucher lookup
- search
- pagination
- aggregate reads

Examples:

```bash
exec ledger-query account Cash
exec ledger-query voucher JV-101
```

Use indexed queries.

Read-only.

---

# generate-report.js

Unified reporting engine.
Produces 12 core reports:
- Trial Balance
- P&L
- Balance Sheet
- Cash Flow
- General Ledger
- AR/AP Aging
- Cash / Bank Book
- Registers (Sales/Purchase)
- Bank Reconciliation
- Audit Report

Derived dynamically from ledger.

---

# reconcile.js

Supports:

- bank reconciliation
- invoice payment matching
- unmatched detection
- duplicate detection

Rules-based matching engine.

---

# integrity-check.js

Critical safety script.

Runs:

```sql
PRAGMA integrity_check;
PRAGMA foreign_key_check;
```

Plus custom checks:

- orphan rows
- duplicate voucher numbers
- unbalanced vouchers
- broken references
- trial balance mismatch

Returns health report.

Run routinely.

---

# close-period.js

Period close engine (Monthly, Quarterly, Yearly).

Steps:
- verify books balanced
- run final reconciliations
- generate closing entries (Yearly: temp accounts to retained earnings)
- lock period

Example:
```sql
period_status='CLOSED'
```

Prevent posting into closed periods without controlled override.

---

# db-maintenance.js

Housekeeping.

Commands:

```sql
VACUUM;
ANALYZE;
PRAGMA wal_checkpoint(FULL);
```

Supports:

- backup
- optimize
- checkpoint
- maintenance

---

# migrate-schema.js

Only allowed schema change path.

Track:

```sql
schema_migrations
```

Never alter schema ad hoc.

---

# Shared Library Rules

Every script should reuse:

```text
lib/db.js
lib/validators.js
lib/posting-engine.js
```

Avoid duplicated logic.

---

# Posting Engine Internal Functions

Recommended internal functions:

```text
validateBalanced()
checkIdempotency()
generateVoucherNo()
postLines()
updateDerivedBalances()
writeAuditTrail()
```

Centralize logic.

All write scripts reuse same engine.

---

# Database Prohibitions

Agent should not issue:

```sql
DELETE FROM ledger
DROP TABLE ...
UPDATE balances ...
```

unless privileged maintenance mode.

Forbidden by default.

---

# Integrity Verification Routine

Run periodically:

```text
integrity-check
trial-balance
reconcile exceptions
backup snapshot
```

Routine order:

```text
verify
repair if needed
backup
continue
```

---

# Backup Rule

Before risky operations:

```bash
cp accounting.db accounting-backup.db
```

Prefer snapshot before:

- close
- migrations
- bulk posting
- rectification batches

---

# Materialized Summary Tables (Optional)

Optional performance layer:

```sql
account_balances
daily_totals
trial_balance_cache
```

Maintain during posting.

Improves reporting speed.

---

# Recommended Dispatcher (Optional)

Optional unified command wrapper:

```text
accounting-cli.js
```

Examples:

```bash
exec accounting-cli post ...
exec accounting-cli tb
exec accounting-cli reconcile
```

Single exec entrypoint.

Preferred for agent simplicity.

---

# Minimal Required Script Set

If creating only minimum set:

```text
post-voucher.js
preview-voucher.js
reverse-voucher.js
trial-balance.js
integrity-check.js
```

Mandatory starter pack.

---

# Agent Execution Preference Order

Always prefer:

1 preview first
2 validated post second
3 append-only corrections
4 scripted operations over ad hoc SQL
5 single write engine over many write paths

Always.

---

# Decision Rule

If operation mutates financial truth:

use script layer.

Do not improvise SQL.

If operation affects integrity:

run integrity-check.

If operation changes schema:

use migrate-schema only.

If operation corrects history:

reverse, never overwrite.

---

# Mental Model

Treat SQLite not as storage.

Treat it as:

```text
mini accounting database kernel
```

Scripts are system calls.

Agent reasons at business level.

Scripts enforce truth.

---

# Final Rule

Prefer:

```text
one database
one write path
one posting engine
many safe script verbs
```

This minimizes:

- tool calls
- hallucinated SQL
- duplicate posting
- integrity failures
- reconciliation problems

and maximizes trust.


path: general_ledger.md
content: # general_ledger.md
# Skill Knowledge File: General Ledger Foundations
# Purpose:
# Teach an Accountant Agent how ledgers are structured,
# how journal entries post into ledgers,
# how balances accumulate,
# and how ledger groups organize postable ledgers.

---

# 1. CORE DEFINITIONS

## Ledger Group

Definition:
A Ledger Group is a classification folder used to organize ledgers.

Examples:
- Assets
- Liabilities
- Equity
- Income
- Expenses

Nested examples:
- Current Assets
- Bank Accounts
- Sundry Creditors

Rules:
- Ledger Groups can contain child groups.
- Ledger Groups can contain Ledgers.
- Ledger Groups do not accept postings.
- Ledger Groups only organize and aggregate.

Hard Rule:

Postings are never made to Ledger Groups.

---

## Ledger

Definition:
A Ledger is a postable account where journal entries are recorded.

Examples:
- Cash
- Bank
- Inventory
- Vendor Payable
- Sales
- Capital
- Drawings

Rules:
- Entries post only to Ledgers.
- Ledgers maintain balances.
- Ledgers can be debited or credited.
- Opening balances belong at Ledger level only.

Hard Rule:

Transactions happen only in Ledgers.

---

# 2. HIERARCHY

Chart of Accounts
  -> Ledger Groups
      -> Ledgers

Example:

Assets
  Current Assets
      Cash
      Bank
      Inventory

Liabilities
  Creditors
      Vendor Payable

---

# 3. RELATIONSHIP

Accounting flow:

Business Event
→ Journal Entry
→ Ledger Posting
→ Running Balances
→ Trial Balance

Journal records events chronologically.

Ledger groups postings account-wise.

---

# 4. LEDGER FORMAT

Use running balance format:

| Date | Voucher | Particulars | Dr | Cr | Balance |

Balance should follow normal account nature.

For Assets/Expenses:
normal balance generally debit.

For Liabilities/Equity/Income:
normal balance generally credit.

---

# 5. POSTING RULE

Every journal entry posts to each impacted ledger separately.

One journal entry creates at least two ledger postings.

Example:

Journal:

Cash Dr 100000
 To Capital 100000

Posts to:

Cash Ledger
Capital Ledger

separately.

---

# 6. PREVIOUS BUSINESS CYCLE EXAMPLES

Using previous journal_entry.md scenarios.

==================================================
CASE 1
Owner invests capital 100000
==================================================

Journal:

Cash Dr 100000
 To Capital 100000

--------------------------------
Cash Ledger
--------------------------------

| Date | Voucher | Particulars | Dr | Cr | Balance |
|------|---------|-------------|----|----|---------|
|1 Jan | OE      | Capital     |100000| |100000 Dr|

--------------------------------
Capital Ledger
--------------------------------

| Date | Voucher | Particulars | Dr | Cr | Balance |
|------|---------|-------------|----|----|---------|
|1 Jan | OE      | Cash        | |100000|100000 Cr|

---

==================================================
CASE 2
Inventory purchased on credit 50000
==================================================

Journal:

Inventory Dr 50000
 To Vendor Payable 50000

--------------------------------
Inventory Ledger
--------------------------------

| Date |Voucher|Particulars|Dr|Cr|Balance|
|-----|------|-----------|--|--|-------|
|2 Jan|PE|Vendor Payable|50000||50000 Dr|

--------------------------------
Vendor Payable Ledger
--------------------------------

|Date|Voucher|Particulars|Dr|Cr|Balance|
|----|------|-----------|--|--|-------|
|2 Jan|PE|Inventory||50000|50000 Cr|

---

==================================================
CASE 3
Cash sale 70000
==================================================

Journal:

Cash Dr 70000
 To Sales 70000

--------------------------------
Cash Ledger
--------------------------------

Opening from Case 1:
100000 Dr

|Date|Voucher|Particulars|Dr|Cr|Balance|
|----|------|-----------|--|--|-------|
|1 Jan|OE|Capital|100000||100000 Dr|
|3 Jan|SE|Sales|70000||170000 Dr|

--------------------------------
Sales Ledger
--------------------------------

|Date|Voucher|Particulars|Dr|Cr|Balance|
|----|------|-----------|--|--|-------|
|3 Jan|SE|Cash||70000|70000 Cr|

---

==================================================
CASE 4
Profit generated
==================================================

Profit:
Sales 70000
Cost 50000
Profit 20000

Optional transfer:

Profit & Loss Dr 20000
 To Retained Earnings 20000

--------------------------------
Retained Earnings Ledger
--------------------------------

|Date|Voucher|Particulars|Dr|Cr|Balance|
|----|------|-----------|--|--|-------|
|4 Jan|JE|Profit Transfer||20000|20000 Cr|

Note:
Profit often emerges from balances and may not require separate daily ledger posting.

---

==================================================
CASE 5
Supplier paid through bank 50000
==================================================

Journal:

Vendor Payable Dr 50000
 To Bank 50000

--------------------------------
Vendor Payable Ledger
--------------------------------

|Date|Voucher|Particulars|Dr|Cr|Balance|
|----|------|-----------|--|--|-------|
|2 Jan|PE|Inventory||50000|50000 Cr|
|5 Jan|BP|Bank|50000||0|

Vendor payable settled.

--------------------------------
Bank Ledger
--------------------------------

|Date|Voucher|Particulars|Dr|Cr|Balance|
|----|------|-----------|--|--|-------|
|5 Jan|BP|Vendor Payable||50000|50000 Cr*

*Assumes no prior funding in bank.
Actual running balance depends on prior entries.

---

==================================================
CASE 6
Owner withdraws profit 20000
==================================================

Journal:

Drawings Dr 20000
 To Cash 20000

--------------------------------
Drawings Ledger
--------------------------------

|Date|Voucher|Particulars|Dr|Cr|Balance|
|----|------|-----------|--|--|-------|
|6 Jan|JE|Cash|20000||20000 Dr|

--------------------------------
Cash Ledger
--------------------------------

Prior balance:
170000 Dr

|Date|Voucher|Particulars|Dr|Cr|Balance|
|----|------|-----------|--|--|-------|
|1 Jan|OE|Capital|100000||100000 Dr|
|3 Jan|SE|Sales|70000||170000 Dr|
|6 Jan|JE|Drawings||20000|150000 Dr|

---

# 7. AGENT POSTING LOGIC

For each journal entry:

For every debit line:
post debit into that ledger.

For every credit line:
post credit into that ledger.

Update running balance.

Never post to ledger groups.

---

# 8. LEDGER OPENING RULE

When user says:

"Open Cash ledger"

Return only transactions posted to Cash ledger.

Do not show unrelated ledger entries.

Support separate viewing per ledger.

Examples:
- Open Bank ledger
- Show Vendor ledger
- Show Sales ledger

---

# 9. VALIDATION RULES

Validate:

- Entries post only to ledgers
- Ledger groups cannot receive postings
- Every journal affects at least two ledgers
- Running balances update after every posting
- Ledger balance must reconcile with journal postings

Reject invalid posting.

---

# 10. LEDGER OBJECT MODEL

Ledger Group:
Name
Parent Group
Postable = No

Ledger:
Name
Parent Group
Account Type
Normal Balance
Opening Balance
Running Balance
Postable = Yes

---

# 11. PRINCIPLE

Ledger Groups classify.

Ledgers transact.

Journal records.

Ledger accumulates.

Trial balance summarizes.

---

# 12. SCOPE LIMIT

This file covers:
- Ledger groups
- Ledgers
- Posting logic
- Running balances

Not covered:
- Trial balance
- Reconciliation
- Financial statements

---
End of general_ledger.md


path: missed_gst_rule.md
content: # Missed GST Detection Rules
Version: 1.0
Layer: Control Skill
Purpose:
Detect omitted, incorrect, underposted or bypassed GST situations.

---

## Definition

Missed GST means:

- GST omitted when applicable
- Wrong GST type used
- Input credit missed
- Output tax missed
- GST embedded incorrectly in expense
- GST not aligned to source document

---

## Detection Rules

Rule 1

IF:
Vendor expense exists
AND no GST component found

Flag:
Possible Missed GST

---

Rule 2

IF:
Taxable sales
AND no output GST

Flag:
Output GST Missing

---

Rule 3

IF:
Expense gross amount includes tax
AND no separate input GST ledger

Flag:
Possible missed ITC

---

Rule 4

IF:
Interstate transaction
AND CGST/SGST used

Flag:
Wrong tax jurisdiction

---

Rule 5

IF:
Intrastate transaction
AND IGST used

Flag:
Wrong tax jurisdiction

---

Rule 6

IF:
GSTIN absent
AND party likely registered

Flag:
GST master incomplete

---

Rule 7

IF:
Manual JE touches GST ledgers

Flag:
Review required

---

Rule 8

IF:
RCM applicable
AND liability side missing
OR credit side missing

Flag:
Incomplete reverse charge posting

---

Rule 9

IF:
Invoice likely eligible for ITC
AND GST booked to expense

Flag:
Input credit may be missed

---

Rule 10

If GST amount mathematically inconsistent:

Taxable Value × Rate ≠ Tax

Flag:
Tax mismatch

---

## Severity

Warning:
Potential issue.

Error:
Wrong posting.

Hard Stop:
Do not post.

---

## Correction Principle

Never silently auto-fix.

Always:
- flag
- explain
- propose corrected entry
- seek confirmation

---

## Agent Message Template

Potential Missed GST Detected:

Reason:
Suggested correction:
Revised entry preview:
Post corrected version? (Y/N)

---

## Core Philosophy

Detect omission before filing problem occurs.

path: tool/package.json
content: {
  "name": "tool",
  "version": "1.0.0",
  "main": "index.js",
  "directories": {
    "lib": "lib"
  },
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "description": "",
  "dependencies": {
    "better-sqlite3": "^11.10.0"
  }
}


path: tool/lib/db.js
content: const Database = require('better-sqlite3');
const path = require('path');

const dbPath = path.resolve(__dirname, '..', 'accounting.db');
const db = new Database(dbPath);

// Enforce strict accounting-grade PRAGMAs
db.pragma('journal_mode = WAL');
db.pragma('foreign_keys = ON');
db.pragma('synchronous = FULL');
db.pragma('busy_timeout = 5000');
db.pragma('temp_store = MEMORY');

module.exports = db;


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