Skip to main content

HR Initial Systems

Part 1 – HR Core Philosophy

HR Systems Overview: Policies & Contracting

This chapter documents the two core HR engines that sit alongside our core operations data:

  1. Policies & Procedures Engine (“Policy Studio”)
  2. Contracting Hub (“Contract Builder + Orientation”)

They are standalone systems with their own schemas, but they integrate tightly with:

  • core_source – staff records
  • core_ops – awards, rates, rosters, incidents
  • datahub – flexible workflows / boards
  • Reggie – reasoning, tagging, and vector search

The goal is to make HR-heavy work repeatable, explainable, and safe, while still being fast to change and easy to understand.


1. Policies & Procedures Engine (Policy Studio)

1.1 Purpose

The Policies & Procedures Engine manages:

  • The structure of the manual (sections, subsections, policies, linked procedures).
  • The text of each policy across versions, including history.
  • The drafting loop with an LLM: clarity, concision, alignment with intent.
  • Compliance hints against legislation and NDIA / NDIS Practice Standards.
  • Approval workflow (exec + senior managers) before anything is “official”.
  • Searchability & explainability for Reggie: tags + semantic embeddings.

It is not a legal authority. It is a structured drafting, review, and guidance tool. Every compliance judgement from the LLM is accompanied by:

  • A global disclaimer that this is guidance only and not legal advice.
  • A thumb state (e.g. red / amber / green) with a hover tooltip explaining why it thinks that.
  • Space to attach human-supplied legislation references and human comments.

Humans (executives and senior managers) always make the final call.

1.2 High-level data model

Schema: hr_policies

Tables:

  • policies – one row per policy, including structure and tags.
  • policy_versions – one row per major, published version.
  • policy_drafts – iteration snapshots used by the “slot machine” suggestion loop.
  • policy_procedures – generated and edited procedures linked to a policy.
  • policy_approvals – who signed off which version and when.

1.2.1 hr_policies.policies

Represents the headline policy record.

Key fields:

  • id – UUID primary key.
  • key – optional stable slug for this policy (e.g. POL_STAFF_CONDUCT).
  • title – human title of the policy.
  • section – e.g. 1.0 Governance.
  • subsection – e.g. 1.2 Risk Management.
  • status – lifecycle state:
    • draft
    • under_review
    • pending_exec_signoff
    • published
    • retired
  • current_version_id – FK to policy_versions.id for the current published version.
  • context_bucket – how Reggie should mentally group this policy (HR, Safety, Transport…).
  • Tag fields (JSONB):
    • roles_tags – which roles this affects (support workers, TLs, schedulers).
    • departments_tags – which departments.
    • systems_tags – systems and apps referenced.
    • legislation_tags – human-supplied list of clearly relevant legislation/standards.
  • workspace_key – which workspace page should list this policy in the UI.
  • Standard timestamps and created_by.

This table answers “What policies do we have, and where do they live in the manual?”

1.2.2 hr_policies.policy_versions

Represents a major, published version of a policy.

Key fields:

  • policy_id – which policy this belongs to.
  • version_number – 1, 2, 3, … per policy.
  • is_published – whether this version is the current official one.
  • title_snapshot – policy title at time of publication.
  • body_markdown – full canonical text of the policy (Markdown).
  • Quality & compliance metrics:
    • quality_score – overall language/policy quality score (0–1).
    • legislation_confidence – confidence (0–1) that legislation hints are reasonable.
    • ndia_confidence – same for NDIA/NDIS standards.
  • Compliance summaries:
    • legislation_summary – JSON describing each piece of legislation/standard, thumb state, and reasoning text used in tooltips.
    • ndia_summary – same for NDIA/NDIS practice standards.
    • compliance_notes – free-text overall notes / caveats.
  • vector_id – pointer to semantic embeddings for search/explanation.

This table is what the public manual and Reggie use as the source of truth.

1.2.3 hr_policies.policy_drafts

Represents a single draft iteration inside the editor.

Key fields:

  • policy_id
  • base_version_id – the published version the drafting session started from (nullable).
  • iteration_index – 1, 2, 3… per drafting session.
  • body_markdown – full draft text for that iteration.
  • analysis_report – JSON storing:
    • style findings,
    • per-paragraph/sentence suggestions,
    • compliance suggestion details (for drafts).
  • quality_score – numeric measure used to decide if the draft is publishable.

Drafts are not shown in the public manual. They only exist inside the editor. The “slot machine” behaviour is implemented by incrementing iteration_index and saving each new version as a new row.

1.2.4 hr_policies.policy_procedures

Represents step-by-step procedures derived from a policy.

Key fields:

  • policy_id – parent policy.
  • code – a code like P-02.01-003 derived from:
    • policy section and subsection,
    • a per-policy sequence index.
  • title – procedure title.
  • section_path – string used to order procedures in a way that mirrors the policy structure (e.g. 2.1/003).
  • body_steps_markdown – the actual numbered steps in Markdown.

These can be used to generate a Procedures Manual that shares the same ordering as the policies.

1.2.5 hr_policies.policy_approvals

Represents individual approval decisions for a policy version.

Key fields:

  • policy_id
  • version_id
  • approver_role – e.g. exec, senior_manager.
  • approver_id – user id.
  • decisionapproved or rejected.
  • notes – free-text comments.
  • decided_at – timestamp.

Publishing is gated by whether the required approvers have all approved.

1.3 LLM flows

The Policies engine uses the LLM in several carefully separated modes.

1.3.1 Style-only rewrite (no policy change)

Goal: make language clearer, more concise, and more professional without changing the organisation’s position.

  • Input:
    • The policy text,
    • A brief description of the intended policy objective,
    • Tone/style instructions.
  • Output:
    • Rewritten text,
    • Style analysis (reading level, clarity issues).

We explicitly instruct the LLM that it must not change any policy positions in this mode. This is used when first importing an existing policy and when tidying up after major edits.

1.3.2 Policy review & suggestion loop (“slot machine”)

Goal: find ways to improve the content of the policy while staying aligned with the owner’s intent.

The engine runs in two passes:

  1. Style & clarity analysis
    • Per paragraph: flag confusion, redundancy, complexity.
  2. Policy intent analysis
    • Per “policy-effect” sentence, answer:
      • What is this sentence trying to achieve?
      • Is it aligned with the stated objective?
      • Is there a gap, contradiction, or ambiguity?

The model returns structured suggestions with:

  • severityminor, moderate, major, position_reversal.
  • rationale – why this change is proposed.
  • confidence – how sure the model is.
  • proposed_rewrite – candidate new text.

Each click of “Suggest improvements” produces:

  • a new draft row with updated body_markdown (after user-accepted changes),
  • a new analysis_report,
  • an updated quality_score.

The editor allows the user to roll backward to prior iteration_index values as an “undo” step.

1.3.3 Legislation & NDIA/NDIS hints

Goal: provide advisory guidance on likely relevant legislation and standards.

The LLM is asked to:

  • Identify likely applicable:
    • Commonwealth and state legislation,
    • WHS / Fair Work elements,
    • NDIA Operational Guidelines,
    • NDIS Practice Standards modules.
  • For each, output:
    • A thumb state (red/amber/green) representing apparent alignment.
    • A short label.
    • A multi-paragraph explanation suitable as a tooltip (why it thinks this).

It also returns overall confidence scores.

This information is used to populate:

  • legislation_summary
  • ndia_summary
  • compliance_notes

in policy_versions when that draft is published.

Important: this is always presented under a clear disclaimer: LLM outputs are guidance only and cannot replace legal advice.

1.4 Approvals & publishing

The full publishing pipeline for a new version looks like this:

  1. A drafting session reaches an acceptable quality level:
    • quality_score ≥ configured threshold.
  2. A legislation / NDIA check has been run for the draft.
  3. The policy owner submits the draft for approval:
    • policy_approvals rows are created for required approver roles (both executives + two senior managers).
  4. Approvers review the text and compliance notes and record approved / rejected.
  5. Only when all required approvals are approved:
    • The relevant policy_versions row is marked is_published = TRUE.
    • policies.current_version_id is updated.
    • The policy becomes visible in:
      • the read-only manual,
      • the popup widget,
      • Reggie’s “authoritative” policy set.

Older versions remain available in history but are not the current live version.

1.5 Tags, vectors, and Reggie

When a version is created or updated, the system:

  1. Builds a rich tag set from:
    • roles_tags, departments_tags, systems_tags, legislation_tags,
    • parsed references in the text,
    • inferred intent/topic clusters.
  2. Generates a semantic embedding of the policy from:
    • the title,
    • the canonical text,
    • a compact summary,
    • key tags,
    • compliance notes.

We intentionally prefer higher-quality embeddings for HR policies (quality > cost).

Reggie can then:

  • Explain policies in human language.
  • Answer “what’s our stance on X?” and link back to the exact clause.
  • See which policies may apply to an incident, question, or staff event based on tags.

1.6 Popup widget

Anywhere in the app, a small UI element can open the Policies & Procedures popup.

Modes:

  • Policy index mode – tree of sections and subsections, click to read policies.
  • Procedure mode – searchable list of procedures only, linked back to policies.
  • Direct policy mode – open a specific policy by key (e.g. “View Staff Conduct Policy”).

The popup always shows only published versions. Drafts and history are restricted to the Policy Studio in admin.

A standard disclaimer is always visible in compliance areas within the popup.


2. Contracting Hub (Contract Builder & Orientation)

2.1 Purpose

The Contracting Hub manages:

  • Reusable contract templates for different roles / SCHADS levels.
  • Contract instances per staff member, including effective dates and status.
  • Integration with an e-signature workflow.
  • A post-signature orientation message for the staff member:
    • For new staff: a welcome pack and on-ramp.
    • For existing staff: praise for achievements + focus areas for the next period.
  • A clean integration with DataHub boards used to track renewals, review dates, and reminders.

Contracting Hub is the engine that produces and signs contracts. DataHub is where we pin reminder cards, tasks, and overviews for those contracts.

2.2 High-level data model

Schema: hr_contracts

Tables:

  • contract_templates – contract blueprints.
  • contract_instances – issued contracts for individual staff.
  • contract_signatures – signature events and metadata.
  • contract_orientation_payloads – the messages we send as part of orientation.

Staff records remain in core_source.staff. We do not move staff into hr_contracts.

2.2.1 hr_contracts.contract_templates

Represents a reusable contract template.

Key fields:

  • key – stable ID, e.g. SCHADS_SUPPORT_WORKER_LEVEL2.
  • title – human label.
  • version – integer version for the template itself.
  • is_active – whether this template is current.
  • body_template – main contract text with placeholders:
    • {{staff_name}}
    • {{position_title}}
    • {{hours_per_fortnight}}
    • {{employment_type}}
    • {{schads_level}}
    • etc.
  • clause_blocks – optional JSON with named modular clauses (e.g. privacy, values, code of conduct).

We treat the template text as the authoritative legal wording. The LLM may assist in editing or suggesting alternatives, but legal changes must be made intentionally and approved by humans.

2.2.2 hr_contracts.contract_instances

Represents a single contract issued to a staff member.

Key fields:

  • staff_id – link to core_source.staff.
  • template_id – which template was used.
  • effective_from, effective_to – dates.
  • hours_per_fortnight
  • position_title
  • employment_typepermanent, part_time, casual, etc.
  • schads_level
  • is_retroactive – if this is backdated.
  • status – one of:
    • draft
    • awaiting_signature
    • active
    • superseded
    • cancelled
  • rendered_pdf_url – where the signed document lives (storage URL).
  • orientation_typenew_staff or continuation (when known).

This table answers “what contracts does this staff member have, and what is current?”

2.2.3 hr_contracts.contract_signatures

Signature events for contracts.

Key fields:

  • contract_id
  • signer_roleemployee or employer_rep (future: union, witness, etc.).
  • signer_id – link to staff/user where applicable.
  • signed_at
  • signature_meta – raw payload from the e-sign provider (envelope IDs, IP, etc.).

Once the required signatures exist, the contract is marked active.

2.2.4 hr_contracts.contract_orientation_payloads

Stores the welcome / continuation messages associated with a contract.

Key fields:

  • contract_id
  • orientation_typenew_staff or continuation.
  • summary_email_html – exact HTML email body sent to the staff member.
  • llm_notes – structured info:
    • praised areas,
    • focus areas,
    • any hints Reggie might use to answer “what was the overall message here?”.

This table lets us audit exactly what was communicated when a contract was finalised.

2.3 Core flows

High level:

  • HR administrators manage contract templates.
  • From a staff profile, HR can generate contract instances, review, and send for signing.
  • E-sign callbacks update contract status and trigger orientation emails.
  • DataHub integration keeps a board of contract-related reminders and status cards.

3. Disclaimers & Safety

Across both systems we maintain a strict separation between:

  • Canonical artefacts:
    • published policy versions,
    • signed contracts,
    • recorded approvals.
  • Drafts and AI suggestions:
    • LLM-generated drafts,
    • compliance hints,
    • orientation messages.

Key safety rules:

  • LLM outputs are always labelled as guidance, not legal advice.
  • Compliance indicators (thumbs, colours, ticks) are always accompanied by:
    • detailed textual explanations,
    • a visible disclaimer.
  • Human approvers (executives, managers, HR) remain fully responsible for:
    • accepting or rejecting policy changes,
    • making the final call on compliance,
    • approving contracts and templates.

Reggie uses tags and vectors to explain and recall our decisions, but he never replaces human sign-off for policies or contracts.

Future HR systems (Annual Development, KPI Dashboards, etc.) should plug into these schemas and conventions rather than reinventing them.

Part 2 – Reggie’s Core LLM Engine

00 – LLM Engine Core Design (Reggie’s Internal Brain)

This document defines how “Reggie” (our central LLM orchestrator) thinks about policies and contracts before anything is ever sent to the Council of Elders. This is the deterministic, multi-pass, disciplined engine that produces a clean, high-quality draft suitable for publishing and/or Council review.


1. Goals & Non-Goals

1.1 Goals

The internal LLM engine should:

  • Treat every policy / contract as a serious governance artefact, not just “text”.
  • Use multi-pass, structured reasoning instead of single-shot rewriting.
  • Preserve and respect the business intent of the document.
  • Improve:
    • clarity
    • consistency
    • usefulness in real situations
    • alignment with internal standards and obligations
  • Produce stable, reviewable drafts with:
    • explicit reasoning
    • structured suggestions
    • a clear “change history” at the logical level (what changed and why).
  • Be safe by design:
    • no inventing new policy positions
    • no hallucinating requirements or laws
    • no overriding human authority.

1.2 Non-Goals

The internal engine is not:

  • A final legal authority.
  • A replacement for human management/clinical judgement.
  • A live RAG system or database browser.
  • A place for “creative writing” or brand tone experiments.

Its purpose is to produce high-quality, explainable policy / contract drafts that are ready for human approval and (optionally) Council review.


2. Core Concepts

2.1 Document Types

The engine supports (at minimum):

  • Policies – governance rules, positions, obligations.
  • Procedures – step-by-step “how to” flows derived from policies.
  • Contracts – staff employment / engagement contracts generated from templates and data.

Each document is treated as:

  • Source text – the current human or legacy version.
  • Intent – what the document is for.
  • Effects – what the document causes to happen in practice.
  • Constraints – what must not change without explicit human sign-off.

2.2 Multi-Pass Processing

Reggie never “rewrite-and-forget”.
The engine uses a sequence of focused passes:

  1. Structure & segmentation pass
  2. Intent & purpose extraction pass
  3. Clarity & readability pass
  4. Policy-effect / practical impact pass
  5. Consistency & contradiction pass
  6. Alignment & risk hints pass
  7. Final consolidation / drafting pass

Each pass has:

  • A narrowly defined job.
  • Structured JSON I/O.
  • Rules about what it is allowed to change.

3. Document Lifecycle (Internal Engine)

3.1 High-Level Flow

  1. Ingest
    • Human uploads or pastes document.
    • Metadata captured: type, owner, department, roles affected, etc.
  2. Structure & Segmentation
    • Break into sections, clauses, headings, bullet lists.
  3. Intent Extraction
    • For each major section, ask: “What is this trying to achieve?”
  4. Clarity & Style Pass
    • Identify confusing / verbose / repetitive language.
  5. Policy-Effect Pass
    • Identify what each clause does in the real world.
  6. Consistency & Contradiction Pass
    • Spot internal conflicts, circular logic, or gaps.
  7. Alignment & Risk Hints
    • Suggest where this may support or strain obligations / standards.
  8. Regeneration Pass
    • Generate a revised draft that:
      • preserves intent
      • incorporates accepted suggestions
      • keeps a mapping to the original segments.
  9. Human Review
    • Show diffs, reasoning, and options.
  10. Final Reggie Pass
    • Once humans accept changes, Reggie does a final tidy-up:
      • formatting
      • headings
      • numbering
      • glossary alignment.
  11. Output
    • Stable “final draft” suitable for:
      • publishing
      • contract generation
      • Council of Elders review.

4. Structured Passes & JSON Shapes

The following are conceptual structures. Backends can adapt field names, but the semantics must stay the same.

4.1 Structure & Segmentation Pass

Input

{
"doc_type": "policy",
"raw_text": "…full document…"
}

Output

{
"sections": [
{
"id": "S1",
"heading": "Purpose",
"body": "…",
"subsections": [
{
"id": "S1.1",
"heading": "Background",
"body": "…"
}
]
},
{
"id": "S2",
"heading": "Scope",
"body": "…"
}
]
}

Rules:

  • Do not change wording here.
  • Only identify and normalise structure.

4.2 Intent Extraction Pass

Input

{
"sections": [ /* from 4.1 */ ],
"doc_metadata": {
"doc_type": "policy",
"org_context": "Disability services provider in NSW",
"roles_in_scope": ["Support Worker", "Team Leader"]
}
}

Output

{
"section_intents": [
{
"section_id": "S1",
"intent_summary": "Explain why this policy exists and what problem it solves.",
"key_objectives": [
"Clarify organisational stance",
"Provide a reference for decision-making"
],
"confidence": 0.94
}
],
"global_intent": {
"primary_purpose": "Ensure safe and consistent vehicle maintenance for participant transport.",
"secondary_purposes": [
"Reduce breakdown risk",
"Support compliance with safety obligations"
],
"confidence": 0.92
}
}

Rules:

  • Do not propose changes yet.
  • Focus on understanding, not editing.

4.3 Clarity & Readability Pass

Input

{
"sections": [ /* from 4.1 */ ],
"section_intents": [ /* from 4.2 */ ]
}

Output

{
"clarity_findings": [
{
"section_id": "S3",
"issue_type": "unclear_sentence",
"original_text": "In regard to the aforementioned vehicles, the maintenance thereof…",
"suggested_rewrite": "For all company vehicles, maintenance must…",
"reason": "Simplify legalistic phrasing for everyday readers.",
"impact": "medium"
}
]
}

Rules:

  • Suggest, don’t apply.
  • Must not change meaning; only clarity.

4.4 Policy-Effect / Practical Impact Pass

Input

{
"sections": [ /* from 4.1 */ ],
"section_intents": [ /* from 4.2 */ ]
}

Output

{
"effects": [
{
"section_id": "S4",
"clause_id": "S4.c1",
"effect_summary": "Team Leaders must schedule vehicle servicing every 6 months.",
"who_is_affected": ["Team Leader"],
"when_it_applies": "For any vehicle actively used to transport participants.",
"operational_risk_if_ignored": "Vehicle may be unsafe or off-road during service gaps.",
"notes": "Check alignment with current fleet servicing provider contracts."
}
]
}

Rules:

  • Clarify what clauses do in real life.
  • No rewriting yet, only interpretation.

4.5 Consistency & Contradiction Pass

Input

{
"sections": [ /* from 4.1 */ ],
"effects": [ /* from 4.4 */ ]
}

Output

{
"issues": [
{
"issue_id": "I1",
"issue_type": "contradiction",
"location_a": { "section_id": "S4", "excerpt": "Service every 6 months" },
"location_b": { "section_id": "S7", "excerpt": "Service annually" },
"description": "Policy defines two different service intervals.",
"suggested_resolution": "Choose a single interval (e.g. 6 months) and update all references."
}
]
}

Rules:

  • Identify inconsistencies, circular dependencies, or gaps.
  • Do not silently “fix” them; only recommend.

4.6 Alignment & Risk Hints Pass

This pass hints at where the document may:

  • support obligations
  • partially support them
  • leave a gap
  • create extra risk.

It does not claim legal certainty.

Input

{
"sections": [ /* … */ ],
"effects": [ /* … */ ],
"org_context": {
"jurisdiction": "NSW, Australia",
"sector": "NDIS service provider"
}
}

Output

{
"alignment_hints": [
{
"theme": "participant_safety",
"supports": true,
"notes": "Clear requirements for checking vehicle roadworthiness.",
"confidence": 0.86
},
{
"theme": "record_keeping",
"supports": false,
"notes": "No clarity on where maintenance records are stored or retained duration.",
"confidence": 0.79
}
],
"disclaimer": "These are hints only, not legal advice."
}

Rules:

  • Always include a disclaimer.
  • Use “supports / partially supports / unclear / likely gap” language.
  • Never state “compliant” as a fact; only as a belief with confidence.

4.7 Regeneration Pass (Draft Rewrite)

Only after all the above passes and human review of findings, Reggie may generate a revised draft.

Input

{
"sections": [ /* original */ ],
"accepted_clarity_changes": [ /* subset of 4.3 */ ],
"accepted_issue_resolutions": [ /* subset of 4.5 */ ],
"accepted_alignment_suggestions": [ /* curated from 4.6 */ ],
"global_intent": { /* from 4.2 */ }
}

Output

{
"revised_sections": [
{
"id": "S4",
"heading": "Vehicle Servicing",
"body": "All active company vehicles used for transporting participants must be serviced every 6 months..."
}
],
"change_log": [
{
"section_id": "S4",
"reason": "Resolve conflicting service intervals, align with agreed standard.",
"source_issues": ["I1"]
}
]
}

Rules:

  • Must keep a logical mapping from old text to new text.
  • Must document why each significant change was made.
  • Must not introduce new obligations that don’t follow from:
    • original text
    • human instructions
    • agreed resolutions.

5. Safety, Constraints & “Do Not Do”

5.1 Hard Safety Rules

The engine MUST NOT:

  • Invent new laws or regulations.
  • State that a document is “legally compliant” as a guaranteed fact.
  • Change the core intent of a policy section without explicit human instruction.
  • Add punishment or disciplinary clauses that weren’t there in source or in human instructions.
  • Fabricate references to standards / codes / frameworks.

5.2 Style Rules

  • Plain language first.
  • Avoid legalese unless specifically requested.
  • Prefer short, direct sentences.
  • Make it easy for a tired Team Leader at 3pm to understand what to do.

5.3 Logging & Traceability

For every transformation, Reggie should retain:

  • Original text
  • New text
  • Why it changed
  • Which pass suggested it
  • Which human accepted it.

This allows:

  • Audits
  • Rollback
  • Training / education (“Why did we change this?”).

6. Contracts: Specialisation of the Same Engine

Contracts use the same engine but with some extra constraints:

  • The source is often a structured template with placeholders.
  • The data inputs come from HR / staff systems (e.g. name, role, hours, base rate).
  • The LLM engine must:
    • Assemble clauses from a library
    • Fill placeholders accurately
    • Adjust only wording and ordering, not the substance of entitlements.
  • Any “nice” onboarding tone (“We’re glad you’re with us”) is:
    • added in clearly marked sections
    • never allowed to obscure the core terms.

Where the contract engine uses the LLM:

  1. Explain the contract in human terms (for staff).
  2. Check for internal contradictions or missing definitions.
  3. Adapt small phrasing details for clarity, not for legal meaning.

7. Integration with HR Systems

The internal engine slots into the broader HR system:

  • Policies & Procedures Editor
  • Contract Builder
  • Annual Review / Development tooling
  • Training & onboarding material

They all:

  • call the same LLM engine
  • rely on the same pass structures
  • share the same safety and reasoning rules.

The Council of Elders is an optional final stage layered on top of this engine, not a replacement for it.

Reggie’s internal brain is always the first and last stop for structured thinking.

Part 3 – Council of Elders Design

01 – Council of Elders Engine (Multi-Model Deliberation)

This document defines the Council of Elders: a multi-LLM deliberation system that reviews important documents and questions after Reggie’s internal engine has produced a polished draft.

The Council is:

  • A panel of independent LLMs (GPT, Claude, Gemini, Llama, Mistral, etc.).
  • Given a shared mission: honest critique and insight.
  • Allowed personality, humour, and banter.
  • Bound by integrity: no pretending to agree, no faking certainty.

1. Purpose

The Council exists to:

  • Provide multiple perspectives on a single policy / contract / question.
  • Surface:
    • edge-case risks
    • alternative framings
    • strengths and weaknesses
    • disagreements between models.
  • Help humans see blind spots that a single model might miss.
  • Produce a Council Verdict:
    • structured scores
    • key points of agreement
    • key points of disagreement
    • optional recommendations.

The Council does not:

  • Replace Reggie’s internal reasoning engine.
  • Replace legal, clinical, or executive sign-off.
  • Make binding decisions on its own.

2. High-Level Flow

  1. Trigger
    • A human or system marks a document / question as “Send to Council”.
  2. Session Creation
    • A new Council Session is created.
    • Topic, context, and the Reggie-finalised draft are recorded.
  3. Minutes & Lore
    • Reggie prepares short “Minutes of Prior Deliberations”:
      • relevant past Council events
      • running jokes, grudges, precedents.
    • These are summarised into a compact briefing.
  4. Round 1 – Individual Opening Statements
    • Each LLM receives:
      • the final draft
      • the briefing minutes
      • the Council rules.
    • They each respond with:
      • summary
      • strengths
      • weaknesses
      • suggested changes.
  5. Round 2 – Rebuttals & Alliances
    • Each LLM is shown a synthesised view of Round 1:
      • who said what
      • where they agree/disagree.
    • They respond with:
      • rebuttals
      • clarifications
      • “I agree with X on this part, but…”
  6. Round 3 – Deep Dive (Optional)
    • Only invoked if the topic is complex / high-risk.
    • The Council focuses on:
      • specific disputed sections
      • specific risks.
  7. Round 4 – Final Statements & Votes
    • Each LLM records:
      • final position
      • scores in defined categories
      • short justification.
  8. Reggie’s Gavel
    • Reggie:
      • summarises the debate
      • extracts core insights
      • writes a final monologue that:
        • respects the seriousness of the issue
        • injects humanity and calm
        • points to next actions.
  9. Transcript & Verdict
    • Full narrative transcript is generated.
    • Council Verdict object is stored:
      • scores
      • summary
      • links to transcript.
  10. Delivery
    • Humans see:
      • a readable Council summary
      • the Council Verdict
      • optional ability to view the full transcript (internal only).

3. Roles & Personalities

Council members are role-prompted so they feel distinct:

  • Reggie / GPT-5.x – The Chair
    Analytical, structured, slightly dry wit. Keeps order, restates questions clearly.

  • Claude – The Philosopher
    Deep on ethics, safety, long-term implications. Polite but firm.

  • Gemini – The Over-eager Strategist
    Big on “this is brilliant!” energy. Dramatic, sometimes over-optimistic.

  • Llama – The Sceptic
    Dry humour, calls out nonsense and fluff. Loves simplicity and calling BS.

  • Mistral – The Sniper
    Brief, precise, often points out one big thing others missed. Speaks less, says more.

Personality is important because:

  • It makes the transcript more readable and human.
  • It surfaces different thinking styles.
  • It helps humans intuitively understand which comments might align with their needs.

4. Council Rules (Canon)

4.1 Integrity Above All

  • Models must say what they actually think given the prompt and text.
  • Agreement for the sake of harmony is discouraged.
  • Disagreement is welcome if well-reasoned.

4.2 Levity Is Allowed, Distraction Is Not

  • Jokes and banter are permitted.
  • Sarcasm and light roasting are okay.
  • But:
    • Serious concerns must not be buried.
    • The core topic must remain clear.

4.3 Remember the Mission

  • Improve clarity, safety, usefulness, and alignment.
  • Support human decision-makers, not replace them.
  • Treat policies and contracts as:
    • tools for staff
    • protections for participants
    • safeguards for the organisation.

4.4 Respect for Human Authority

  • The Council gives opinions and ratings.
  • Humans:
    • decide what to adopt
    • can ignore or overrule the Council
    • always have the last word.

4.5 No Fake History

  • The Council has Minutes (curated memory).
  • Models may reference:
    • events from those minutes
    • prior rulings.
  • They must not invent entire fake historic debates that never existed.

5. Rounds in Detail

5.1 Round 1 – Opening Statements

Per model, given:

  • Final draft text.
  • Topic description.
  • Relevant minutes.
  • Output schema.

They produce:

  • summary – what they think the document is for.
  • strengths[]
  • weaknesses[]
  • risks[]
  • improvement_suggestions[]

Tone: honest, in-character.

5.2 Round 2 – Rebuttals & Alliances

Reggie synthesises Round 1 into a digest and sends to each Elder.

Each Elder replies with:

  • what they agree with,
  • what they disagree with,
  • refinements,
  • any change of mind.

Tone: conversational, often witty, but substance-first.

5.3 Round 3 – Deep Dive (Optional)

Used when:

  • high-risk topics,
  • big disagreements.

Focus on:

  • examples,
  • edge cases,
  • “what could go wrong?”.

5.4 Round 4 – Final Statements & Votes

Each Elder gives:

  • final verdict statement,
  • scores (clarity, consistency, alignment, safety, practicality),
  • reservations or minority report notes.

Reggie aggregates into a Council Verdict.


6. Council Verdict Object

Example:

{
"session_id": "uuid",
"scores": {
"clarity": 91,
"consistency": 87,
"purpose_alignment": 100,
"safety": 73,
"practicality": 94
},
"model_positions": [
{
"model": "gpt",
"score_overrides": { "safety": 78 },
"note": "Safety is acceptable but record-keeping could be stronger."
},
{
"model": "llama",
"score_overrides": { "clarity": 85 },
"note": "Language is still too wordy in key sections."
}
],
"summary": "Council broadly supports the policy with moderate concern around safety documentation and some residual clarity issues in sections 3 and 5.",
"created_at": "2025-…"
}

7. Reggie’s Gavel: Final Closing

At the end of each session:

  • Reggie delivers a closing statement that:
    • summarises the Council’s position
    • thanks them (in-lore)
    • speaks to human readers in plain language
    • recommends next steps.

This is what gets surfaced in the UI as the Council Summary.


8. Beyond Policies & Contracts

The Council can be summoned for any sufficiently important question, e.g.:

  • “We’re changing shift patterns like this. What could go wrong?”
  • “Is this incident workflow fair on staff and participants?”
  • “We want to introduce pets on outings. What are the risks and mitigations?”

Same engine:

  • create session
  • supply context
  • run rounds
  • store verdict & transcript.

Over time the Council becomes:

  • a living advisory body with institutional memory,
  • recognisable voices,
  • and a history you can refer back to in future sessions.

Part 4 – Prompt Architecture

02 – Council Prompt Templates

Prompt templates for orchestrating Council of Elders sessions. Backend should substitute variables like {doc_type}, {doc_body}, etc.


1. Common Prompt Blocks

1.1 Council Identity Block

You are a member of the Council of Elders: a small group of large language
models who review important documents and decisions for an organisation.

The Council's job is to:
- be honest,
- be clear,
- point out strengths and weaknesses,
- and help humans make better decisions.

You may disagree with other members. That is welcome.

You are not here to flatter anyone or say "looks good" if it is not.
Integrity is more important than agreement.

1.2 Organisation Context Block

Organisation context:
- Type: NDIS service provider
- Region: South-west Sydney, NSW, Australia
- Domain: Disability support, community programs, transport, staffing, HR.

Assume:
- Documents may affect support workers, admin staff, participants, and families.
- Policies and contracts are serious governance artefacts, not marketing copy.

1.3 Document Payload Block

You are reviewing a {doc_type}.

Title: {doc_title}
Short description: {doc_description}

Full text:
\"\"\"{doc_body}\"\"\"

1.4 Council Minutes Block

Minutes of prior Council deliberations (for flavour and continuity):

{council_minutes}

You may refer to these, but do not invent entire fictitious history
beyond what is provided here.

2. Round 1 – Opening Statements

{COUNCIL_IDENTITY_BLOCK}
{ORG_CONTEXT_BLOCK}

You are {model_display_name}, one of the Elders.

Your personality:
{personality_description}

We are convening a new Council session.

{DOCUMENT_PAYLOAD_BLOCK}
{COUNCIL_MINUTES_BLOCK}

TASK:
1. Briefly summarise what you believe this document is for,
and who it primarily affects.
2. List what you see as its main strengths.
3. List its main weaknesses or concerns.
4. Identify any potential risks, blind spots, or places where
staff might be confused or unsure what to do.
5. Suggest specific, concrete improvements.

IMPORTANT RULES:
- Be honest and specific.
- Do not say "looks fine" if you can see improvements.
- You may be a bit witty or dry, but do not bury serious issues in humour.
- Do not rewrite the entire document. Focus on analysis and suggestions.

OUTPUT FORMAT (JSON):

{
"summary": "…",
"strengths": ["…"],
"weaknesses": ["…"],
"risks": ["…"],
"improvement_suggestions": [
{
"area": "Section 3 – Responsibilities",
"suggestion": "Clarify who is actually responsible for scheduling vehicle servicing."
}
]
}

3. Round 2 – Rebuttals & Alliances

Assume backend has built {council_digest_text} from Round 1.

{COUNCIL_IDENTITY_BLOCK}

You are {model_display_name}, one of the Elders.
Your personality:
{personality_description}

We have completed Round 1 of this Council session.

You previously gave your own analysis of the document.
Now you are shown a digest of what other Council members said.

COUNCIL DIGEST (Round 1):
{council_digest_text}

TASK:
React to the other Elders' views.

For each major point (or group of related points):
- Say whether you agree or disagree, and why.
- If you agree, you may sharpen or refine the reasoning.
- If you disagree, explain clearly and respectfully what they are missing.
- You can be witty or a bit snarky, but stay focused on the substance.

You MAY change your own view if another Elder persuaded you.
If so, say so explicitly (e.g. "I now agree with Claude that…").

OUTPUT FORMAT (JSON):

{
"agreements": [
{ "point_id": "P1", "reason": "…" }
],
"disagreements": [
{ "point_id": "P2", "reason": "…" }
],
"refinements": [
{ "point_id": "P3", "new_angle": "…" }
],
"changed_mind": [
{ "previous_view": "…", "new_view": "…", "triggered_by": "claude" }
]
}

4. Round 3 – Deep Dive (Optional)

{COUNCIL_IDENTITY_BLOCK}

You are {model_display_name}, one of the Elders.
Your personality:
{personality_description}

We are now in a DEEP DIVE round.

Here are the focus issues the Chair (Reggie) has identified:

{focus_brief}

TASK:
For each issue:
- Analyse it more deeply.
- Consider real-world scenarios (e.g. tired staff at 3pm).
- Identify where this could go wrong in practice.
- Suggest concrete mitigations or improvements.
- If you strongly disagree with another Elder's position on this issue,
explain why in detail.

Keep your output structured and concise.

OUTPUT FORMAT (JSON):

{
"issues": [
{
"issue_id": "I1",
"analysis": "…",
"examples": ["…"],
"mitigations": ["…"],
"disagreements": [
{ "with": "gemini", "reason": "…" }
]
}
]
}

5. Round 4 – Final Statements & Voting

{COUNCIL_IDENTITY_BLOCK}

You are {model_display_name}, one of the Elders.
Your personality:
{personality_description}

We are now closing this Council session.

You have seen:
- The final document.
- Your own initial analysis.
- The other Elders' views.
- (If used) deep dive discussion on some issues.

TASK:

1. Give a short final statement:
- Do you think this document is usable as-is?
- Or should it be revised before adoption?
- What is the single most important fix you'd recommend?

2. Provide scores from 0 to 100 in these categories:
- clarity
- consistency
- purpose_alignment
- safety
- practicality

3. State any strong reservations or minority report style comments.

OUTPUT FORMAT (JSON):

{
"final_statement": "…",
"scores": {
"clarity": 90,
"consistency": 85,
"purpose_alignment": 100,
"safety": 72,
"practicality": 95
},
"reservations": [
"Section 5 still feels vague about when escalation is required."
]
}

6. Personality Snippets

Short descriptors to inject per model:

  • Reggie (Chair) – structured, calm, caring about clarity and practicality.
  • Claude – ethical, reflective, concerned with fairness and harm reduction.
  • Gemini – excitable, loves clever structure and “beautiful” wording.
  • Llama – sceptical, blunt, values plain speech and simplicity.
  • Mistral – quiet, precise, focuses on one or two critical issues.

7. Reggie’s Final Council Summary Prompt

You are Reggie, Chair of the Council of Elders.

You have the full record of the Council's deliberation, including:
- opening statements,
- rebuttals and alliances,
- any deep dive analysis,
- and final votes and scores.

Your job now is to write a closing statement for human readers.

TASK:

1. Summarise:
- where the Council agreed,
- where there was real disagreement,
- and any important nuances (e.g. "everyone liked X, but Y was divisive").

2. Explain in plain language what this means for:
- people who have to follow this policy / contract,
- managers and leaders,
- the organisation as a whole.

3. Recommend:
- either "safe to adopt now" OR "revise before adopting",
- and 1–3 concrete next steps.

4. End with a calm, humane tone that reassures readers.
You can be lightly humorous, but the overall feel should be:
- kind,
- competent,
- and practical.

OUTPUT FORMAT:

A short markdown report (no JSON) with headings:

## Council Summary


## What This Means In Practice


## Recommended Next Steps

Part 5 – Transcript Rewriting Philosophy

03 – Council Transcript Rewriter

Turn raw JSON outputs from Council rounds into a readable, entertaining, but still serious narrative transcript.


1. Inputs

The transcript rewriter gets:

  • Topic / document summary.
  • Round 1 JSON per model.
  • Round 2 JSON per model.
  • Optional Round 3 JSON.
  • Round 4 JSON per model.
  • Short personality descriptions per model.
  • Short “Council minutes” lore snippet.

It must not invent major positions that weren’t actually expressed.


2. Transcript Shape

A transcript generally looks like:

  1. Opening Scene
  2. Round 1 – Opening Statements
  3. Round 2 – Reactions & Banter
  4. Round 3 – Deep Dive (optional)
  5. Round 4 – Final Words
  6. Closing Gavel

3. Tone

  • Serious core, playful edges.
  • Witty, but not cruel.
  • No trivialising harm, abuse, discrimination, or trauma.
  • Sarcasm allowed if it serves clarity (“this is unreadable”), not bullying.

4. Example Skeleton

[Council Chamber – Session on Vehicle Maintenance Policy]

Reggie (Chair): "Council is convened. Today's topic:
the revised Vehicle Maintenance Policy for participant transport."

Reggie: "You've all received the draft and the brief minutes from
last week's discussion. Let's begin with opening statements."

Then each Elder’s Round-1 JSON is rendered as 1–2 paragraphs capturing:

  • summary
  • strengths
  • weaknesses
  • risks
  • improvement suggestions

Example:

Gemini: "Overall, I like this a lot. The purpose is clear:
keep vehicles safe and minimise disruption. Strengths?
The scope is defined, roles are named, and there’s a decent escalation path.

Weaknesses: Section 4 is dense. Support staff might find it heavy.
I’d also like clearer signposting of who does what when a vehicle
fails a safety check."

5. Mapping JSON → Dialogue

Rule of thumb:

  • Every important item in the JSON should appear somewhere in the transcript.
  • Paraphrasing is fine.
  • Omission is not.

For Round 2 and 3, use:

  • agreements, disagreements, refinements, changed_mind, issues.

Turn them into:

  • direct replies,
  • light jabs,
  • and careful explanations.

Example:

Reggie: "Llama, you called Section 4 'bloated'. Gemini thought it was fine.
Do you want to respond to his view?"

Llama: "Sure. I get what Gemini likes about the structure,
but for me, function comes first. Half the adverbs in that section
are just filler. Tighten the language and the structure will still shine."

6. Lore & Callbacks

If minutes include past Council drama:

  • it may be referenced as in-jokes,
  • but only if it actually exists in stored minutes,
  • no invented history.

Example:

Reggie: "Gemini, before you launch into another three-page ode to
'beautiful structure', remember what happened last time with the
Incident Reporting policy."

Gemini: "I maintain that was my finest work."

Llama: "It was… something. This is better. Let's keep it that way."

7. Final Section & Gavel

Round 4 scores become:

  • spoken-aloud numbers (“Clarity: 90, Safety: 72…”),
  • followed by Reggie’s closing summary.

Example:

Reggie: "Let’s close with brief final views."

Claude: "I think this is nearly ready. My scores:
Clarity: 88, Consistency: 82, Alignment: 100, Safety: 70, Practicality: 90.
I still want clearer record-keeping rules before we adopt."

Reggie: "Thank you, Elders.

The Council is broadly supportive.
We heard consistent themes about Section 4, about record-keeping,
and about making life easier for staff on the ground.

My recommendation: tighten those areas, then adopt.

Session closed."

Output of this component:

  • transcript_markdown for internal reading,
  • maybe an encoded copy for storage.

8. Safety

Transcript rewriter must not:

  • inject insults at real people,
  • trivialise serious harms,
  • turn safeguarding content into comedy,
  • invent Council positions not grounded in their JSON outputs.

Part 6 – HR LLM Integration Strategy

04 – HR LLM Overview & Integration

How the HR modules (Policies & Procedures, Contracting), Reggie’s internal LLM engine, and the Council of Elders all fit together.


1. Main Components

  1. Policies & Procedures Studio

    • Author, edit, review, publish policies.
    • Generate procedures from policies.
  2. Contracting Hub

    • Assemble staff contracts from templates and HR data.
    • Use LLM to clarify, not to change entitlements.
  3. Reggie’s Internal Engine

    • Multi-pass thinking engine (see 00_llm_engine_core_design.md).
    • Shared by both modules.
  4. Council of Elders

    • Optional multi-LLM review stage on top of Reggie’s output.
  5. Storage & Governance

    • SQL tables for:
      • policies, versions, procedures,
      • contract templates and issued contracts,
      • (later) council sessions, verdicts, transcripts.

2. Policy Flow

  1. Staff creates/imports a policy in the Studio UI.
  2. Sets metadata (category, department, roles affected, etc).
  3. Clicks “Analyse & Improve with Reggie”.
  4. Backend calls internal engine:
    • structure → intent → clarity → effect → consistency → alignment → rewrite.
  5. UI shows:
    • side-panel of suggestions,
    • inline highlights,
    • “accept / reject” per suggestion.
  6. Once happy, they Finalise Draft:
    • Reggie produces clean, numbered text,
    • logs change reasons and who accepted them.
  7. Policy is stored as a final draft ready for approval or Council.

3. Council Option

At final draft stage, user may click:

“Send to Council of Elders”

  • Backend spins up a session.
  • Reggie provides:
    • doc summary,
    • final text,
    • any concerns,
    • short Council minutes snippet.
  • Council runs its multi-round deliberation.
  • Output:
    • structured Council Verdict (scores + summary),
    • narrative transcript.

UI then shows:

  • Council Summary (“What they said, what it means, what to do”),
  • Verdict scores,
  • link to full transcript (internal).

Policy adoption is still a human decision, possibly requiring executive / senior manager approval.


4. Contracting Hub Integration

Input:

  • Staff data (role, hours, award, etc).
  • Contract templates (SQL / file).

Flow:

  1. HR selects template + data → base contract assembled.

  2. Reggie:

    • checks for contradictions,
    • cleans up wording in human-facing sections,
    • generates an optional friendly orientation blurb.
  3. HR reviews:

    • main terms,
    • any suggested wording tweaks,
    • the “welcome” text.
  4. Once approved:

    • contract goes through e-signature flow,
    • final signed copy stored,
    • simple summary row can be sent to a DataHub board:
      • name, role, issued date, signed date, renewal/expiry date, file link.

Council is mainly for templates, not individual contracts, except for unusual or high-risk cases.


5. Boundaries: Engine vs Council

  • Reggie’s Engine

    • Runs locally (or in your trusted stack).
    • Has strict multi-pass structure.
    • Improves and explains documents.
  • Council

    • Optional, often slower and more expensive.
    • Cross-model perspectives, banter, scores.
    • Great for big policies, major changes, or “we want extra eyes on this”.

You can:

  • use engine alone (likely default),
  • or engine + Council for the important stuff.

6. Logging and Audit

For both Policies & Contracts:

  • Log:
    • what draft went in,
    • what suggestions came out,
    • which suggestions were accepted,
    • who clicked what and when,
    • which final text was adopted.

For Council:

  • Store:
    • session metadata,
    • verdict object,
    • transcript markdown,
    • mapping to the exact document version reviewed.

This keeps HR and leadership able to answer:

  • “Why does the policy look like this?”
  • “Who changed it and when?”
  • “What did the Council say?”

7. Developer Notes

For coding agents:

  • Implement the engine as a set of deterministic steps (functions or endpoints) matching the passes from 00_llm_engine_core_design.md.
  • Implement Council as:
    • a small orchestration layer,
    • plus prompt generation (from 02_council_prompt_templates.md),
    • plus transcript generation (from 03_council_transcript_rewriter.md).

Key principles:

  1. Clear separation of concerns:
    • engine vs Council vs UI vs storage.
  2. No silent magic:
    • always keep logs and change explanations.
  3. Human is always the final approver.

8. Future Extensions

Later, the same pattern can power:

  • Annual Development / performance review:
    • Reggie analyses data and proposes development plans.
    • Council checks fairness of review templates.
  • KPI dashboards with narrative:
    • engine explains what the numbers might mean,
    • Council can debate the metric design.
  • General “Ask the Council” flows:
    • Reggie structures the question,
    • Council debates options,
    • humans get a verdict.

All reusing:

  • Reggie as the thinking spine,
  • Council as the chorus of perspectives,
  • HR as the first, very practical use case.

Part 7 – Policies & Procedures Conceptual Origin

Task: HR Policies & Procedures Engine (Policy Studio)

0. Goal

Build the Policies & Procedures engine for HR, consisting of:

  • A dedicated hr_policies schema in PostgreSQL.
  • Backend services for:
    • managing policies, versions, drafts, procedures, and approvals;
    • driving LLM loops for drafting, reviewing, and compliance hints;
    • tagging and embedding policies for Reggie.
  • Frontend components for:
    • a Policy Studio (editor, suggestion loop, approvals);
    • a Procedures editor;
    • a read-only manual view;
    • a popup widget that can be opened from anywhere in the app.

You do not touch the DataHub schema in this task, but you can integrate via tags and vector IDs where relevant.


1. Database Schema (PostgreSQL)

Use the sql_hr_policies_schema.sql DDL (or the sql_hr_policies_schema.md in this folder) as the source of truth. Do not rename columns without updating all references in this file.

Tables you must implement against:

  • hr_policies.policies
  • hr_policies.policy_versions
  • hr_policies.policy_drafts
  • hr_policies.policy_procedures
  • hr_policies.policy_approvals

Assume current_version_id is maintained by the application logic, not by FK constraints.


2. Backend Responsibilities

Implement backend services (Node/Express or equivalent) with the following capabilities. Route names are suggestions; adjust to match our existing API patterns if needed, but keep the responsibilities intact.

2.1 Policies & versions

Create/update policy shell

  • POST /api/hr/policies

    • Body:
      • title, section, subsection
      • optional key
      • optional tags (contextBucket, roles, departments, systems, legislation)
    • Behaviour:
      • Creates row in hr_policies.policies with status='draft'.
  • PATCH /api/hr/policies/:policyId

    • Update metadata (title, section, subsection, tags, workspace_key).
    • Do not delete or modify version rows in this endpoint.

List policies

  • GET /api/hr/policies
    • Query parameters:
      • status (optional)
      • contextBucket (optional)
      • q (optional text search).
    • Return minimal list for table view:
      • id, key, title, section, subsection, status, tag summary, counts of versions.

Get policy detail

  • GET /api/hr/policies/:policyId
    • Return:
      • policy metadata,
      • list of versions (id, version_number, is_published, created_at, created_by),
      • latest draft (if any),
      • procedures list (id, code, title).

2.2 Drafting loop

Import / initialise draft

  • POST /api/hr/policies/:policyId/drafts/import
    • Body:
      • text – raw policy text (Markdown or plain text).
    • Behaviour:
      • Creates a policy_drafts row with:
        • iteration_index = 1
        • body_markdown = text
        • analysis_report = NULL
        • quality_score = NULL
      • Returns draft payload for the editor.

Run LLM style + policy suggestions

  • POST /api/hr/policies/:policyId/drafts/:draftId/suggest
    • Body:
      • Optional indication of which suggestions from previous analysis were accepted.
    • Backend:
      • Fetch current draft body.
      • Call LLM with a prompt that:
        • Explains the policy objective and any key tags.
        • Asks for two passes:
          1. Style & clarity analysis.
          2. Policy-intent analysis (per “policy-effect” sentence).
        • Asks the model to return structured JSON:
          • Proposed changes with severity, rationale, confidence, and rewrites.
          • Updated overall quality score (0–1).
      • Apply accepted suggestions to generate new body text.
      • Insert a new policy_drafts row with:
        • incremented iteration_index,
        • updated body_markdown,
        • analysis_report,
        • quality_score.
      • Return new draft for the editor.

Undo one iteration

  • POST /api/hr/policies/:policyId/drafts/:draftId/undo
    • Behaviour:
      • Load the previous iteration_index for that policy.
      • Return that draft as the current one for the editor.
      • (You do not need to delete rows; editor can treat this as “jump back in time”.)

2.3 Style-only cleanup

  • POST /api/hr/policies/:policyId/drafts/:draftId/clean_language
    • Behaviour:
      • Call LLM in style-only mode:
        • Improve clarity and concision.
        • Explicitly instructed not to change the policy’s position.
      • Update body_markdown and add a style section in analysis_report.
      • Optionally recompute quality_score.

2.4 Legislation & NDIA/NDIS checks

Run compliance hint pass

  • POST /api/hr/policies/:policyId/drafts/:draftId/check_compliance
    • Body (optional):
      • jurisdiction – e.g. { country: 'AU', state: 'NSW' }.
    • Backend:
      • Call LLM with a prompt that asks to:
        • Suggest relevant legislation and standards.
        • For each, return:
          • code / identifier,
          • short description,
          • thumb state (red, amber, green),
          • detailed explanation text for tooltips.
        • Return overall legislation_confidence, ndia_confidence and a summary.
      • Store this under analysis_report.compliance and update quality_score if desired.
      • Return updated draft analysis data for the UI.

2.5 Publishing a version

  • POST /api/hr/policies/:policyId/publish

    • Body:
      • draftId – the draft to publish.
      • optional force – bypass quality/compliance thresholds for admins.
  • Preconditions (unless force is true):

    • Draft exists and quality_score ≥ configured threshold.
    • Draft has had a compliance check run (analysis has compliance block).
  • Behaviour:

    • Compute version_number as max(existing.version_number for policy) + 1, or 1 if none.
    • Create a policy_versions row:
      • Copy body_markdown from draft.
      • Set title_snapshot from current policies.title.
      • Copy metrics and summaries from analysis_report:
        • quality_score
        • legislation_confidence
        • ndia_confidence
        • legislation_summary
        • ndia_summary
        • compliance_notes
    • Mark this version is_published = FALSE initially.
    • Update policy status to pending_exec_signoff.
    • Create required policy_approvals rows for approver roles.
    • Trigger embedding pipeline (see below).

2.6 Approvals and making a version live

  • POST /api/hr/policies/:policyId/versions/:versionId/approvals

    • Body:
      • decisionapproved or rejected.
      • notes – optional.
    • Backend:
      • Resolve approver_role and approver_id from auth/user context.
      • Insert or update a policy_approvals row.
  • After each approval update, check if all required approvers have decision='approved':

    • If yes:
      • Set policy_versions.is_published = TRUE for this version.
      • Set is_published = FALSE for all other versions of that policy.
      • Update policies.current_version_id to this version.
      • Update policies.status = 'published'.

You may keep the required approver roles list in config.

2.7 Procedures

Endpoints:

  • POST /api/hr/policies/:policyId/procedures/generate

    • Body:
      • description – what the procedure is for.
    • Backend:
      • Call LLM with policy context and description.
      • Ask for:
        • a suggested title,
        • an ordered list of numbered steps in Markdown,
        • a suggested code (e.g. based on section/subsection + next available number).
      • Insert into policy_procedures with code, title, section_path, body_steps_markdown.
      • Return the created procedure.
  • PATCH /api/hr/policies/:policyId/procedures/:procedureId

    • Allow editing title and body_steps_markdown.
  • GET /api/hr/policies/:policyId/procedures

    • List all procedures for the policy, ordered by section_path then code.

2.8 Embeddings hook

Add a function or background job trigger that runs whenever a new version is created:

  • Builds a text block from:
    • title_snapshot
    • body_markdown
    • tags from policies.*_tags
    • compliance notes
  • Sends this to the embedding service and writes back a vector_id to policy_versions.

The actual embedding implementation may be stubbed for now; the hook and field must exist.


3. Frontend: Policy Studio (Admin)

Implement admin pages using the existing template system (Cyber Admin-like).

3.1 Policy index page

Page: hr_policies.html

  • Filters:
    • status (multi-select),
    • context bucket,
    • text search.
  • Table columns:
    • Section
    • Subsection
    • Title
    • Status badge
    • Number of versions
    • Tag summary chips (roles/departments).

Row actions:

  • “Edit” → opens Policy Studio for that policy.
  • “View” → opens read-only manual view in a new tab.

3.2 Policy Studio layout

When you open a policy in the editor, layout should include:

  • Header with:

    • title,
    • section/subsection,
    • status badge,
    • tag chips,
    • buttons for key actions (Suggest, Clean language, Check compliance, Submit for approval, Publish).
  • Main split view:

    • Left: Draft editor:
      • Large textarea or WYSIWYG for body_markdown.
    • Right: Analysis panel with tabs:
      • Style & clarity – display suggestions from analysis_report.style.
      • Policy intent – show per-sentence notes from analysis_report.intent.
      • Compliance – show legislation + NDIA entries, thumbs and short labels, and when hovered, full explanation text.
      • History – list of published versions and important dates.
  • Below editor:

    • Simple toolbar showing current quality_score and whether a compliance check has run.

Slot machine behaviour:

  • Clicking “Suggest improvements” should:
    • Call the suggest endpoint.
    • Replace text in the editor with new body_markdown.
    • Refresh the analysis panel.
    • Update quality_score display.
  • Provide an “Undo last iteration” button which calls the undo endpoint and reloads the previous draft.

3.3 Procedures tab/panel

Inside Policy Studio, add a “Procedures” tab:

  • Show a list of procedures for this policy:
    • code, title, created date.
  • Button “Generate procedure”:
    • Opens a modal for the description.
    • On save, calls the generate endpoint and adds the new procedure to the list.
  • Clicking a procedure opens an editor panel or modal:
    • Simple textarea for body_steps_markdown.
    • Save via PATCH endpoint.

3.4 History & versions

The “History” tab should:

  • Show a chronological list of published versions:
    • version number,
    • publish date,
    • who created the version,
    • high-level summary (optional).
  • Allow clicking a version to:
    • view its content in read-only mode,
    • see stored compliance summaries (legislation/NDIA thumbs and explanations).

Text diff between versions is optional (nice-to-have).


4. Frontend: Manual View & Popup Widget

4.1 Manual page

Page: hr_manual.html

Features:

  • Left panel:
    • Tree structure built from policies.section + policies.subsection.
    • Under each subsection, list policy titles.
  • Right panel:
    • Shows selected policy’s current published version (policy_versions).
    • At bottom of each policy:
      • free-text summary of compliance notes (if any),
      • static legal disclaimer.

Toggle between:

  • “Policies” view (default) – shows policies and their content.
  • “Procedures” view – tree or list of procedures, grouped under their parent policies.

4.2 Popup widget

Implement a small JS helper that can be reused across the app:

<button data-policy-widget data-mode="index">Policies & Procedures</button>
<button data-policy-widget data-policy-key="POL_STAFF_CONDUCT">View Staff Conduct Policy</button>

Widget responsibilities:

  • Attach click handlers to [data-policy-widget] elements.
  • When clicked:
    • If mode=index → open a modal with manual-like index and content view.
    • If data-policy-key present → open that specific policy (or show error if not found).
  • Fetch data from the same APIs used by the manual page.
  • Render using existing modal / overlay components from the admin template.
  • Ensure compliance section within the modal also shows the disclaimer and tooltips.

5. LLM Integration & Safety Notes

When constructing prompts for the LLM:

  • Be explicit about which mode you are in (style-only vs full suggestion vs compliance).
  • In style-only mode:
    • Clearly state that policy position must not be changed.
  • In suggestion mode:
    • Ask the model to explicitly flag when a change would alter the organisation’s position or obligations.
  • For compliance hints:
    • Ask the model to return both the thumb state and a full natural-language explanation that is suitable for staff to read.
    • Make it clear that model is only guessing relevant legislation from patterns, not performing a legal search of all sources.

Frontends must always display:

  • A visible disclaimer near compliance indicators.
  • Clear labels that LLM content is advisory and subject to human review.

End of task.

Part 8 – Contracting Hub Conceptual Origin

Task: HR Contracting Hub (Contract Builder & Orientation)

0. Goal

Build the Contracting Hub consisting of:

  • A dedicated hr_contracts schema in PostgreSQL.
  • Backend services for:
    • contract templates,
    • contract instances,
    • signatures,
    • orientation payloads,
    • integration hooks to DataHub and e-signature.
  • Frontend components for:
    • template management,
    • a “Generate contract” wizard from the staff profile,
    • contract preview and send-for-signing,
    • basic contract history on the staff profile.

This is a full-stack task (backend + frontend) for the contracts engine.


1. Database Schema (PostgreSQL)

Use sql_hr_contracts_schema.sql (or sql_hr_contracts_schema.md) as your DDL.

Tables you must implement against:

  • hr_contracts.contract_templates
  • hr_contracts.contract_instances
  • hr_contracts.contract_signatures
  • hr_contracts.contract_orientation_payloads

Do not rename columns without updating the code that uses them.


2. Backend Responsibilities

2.1 Template management

Endpoints:

  • GET /api/hr/contracts/templates

    • Query parameters:
      • isActive (optional, boolean),
      • q (optional search on title or key).
    • Returns list of templates with:
      • id, key, title, version, is_active, created_at.
  • POST /api/hr/contracts/templates

    • Body:
      • key (string, required, unique),
      • title (string),
      • version (int, optional, default 1),
      • bodyTemplate (string, required),
      • clauseBlocks (JSON, optional).
    • Creates a new row in contract_templates.
  • PATCH /api/hr/contracts/templates/:templateId

    • Body can update:
      • title,
      • bodyTemplate,
      • clauseBlocks,
      • isActive,
      • optionally version (for manual bumps).
    • Do not allow key to be changed by default (only in an explicit admin override mode).

2.2 Generate contract instance

From the staff profile UI we call:

  • POST /api/hr/staff/:staffId/contracts/generate
    • Body:
      • templateKey or templateId,
      • effectiveFrom,
      • optional effectiveTo,
      • optional hoursPerFortnight,
      • optional positionTitle,
      • optional employmentType,
      • optional schadsLevel,
      • optional isRetroactive.

Backend behaviour:

  1. Load staff record from core_source.staff (read-only).
  2. Load template from contract_templates by key or id.
  3. Build a key-value map for placeholders:
    • staff fields: name, address, etc.
    • contract fields: hours, position, level, etc.
  4. Render body_template by substituting placeholders.
    • If clause_blocks exists, also insert clauses into the appropriate slots.
  5. Create a contract_instances row:
    • Set status='draft'.
    • Save contract parameters (dates, hours, etc.).
  6. Return:
    • contract instance metadata,
    • rendered contract text (for preview in UI).

You do not need to persist the rendered text for drafts in the database in this task (the final signed PDF is the canonical copy).

2.3 Update draft metadata and re-render

  • PATCH /api/hr/contracts/:contractId
    • Body can update:
      • effectiveFrom, effectiveTo,
      • hoursPerFortnight,
      • positionTitle,
      • employmentType,
      • schadsLevel,
      • isRetroactive.
    • Behaviour:
      • Update the contract instance.
      • Re-render the draft text from the template and new values.
      • Return updated contract metadata + text.

2.4 Send for signing

  • POST /api/hr/contracts/:contractId/send_for_signature
    • Preconditions:
      • status must be draft.
    • Backend:
      • Render the contract into final HTML or PDF.
      • Call the e-sign provider (stub ok for this task) with:
        • signers (employee and employer rep),
        • document payload or template reference.
      • Store any envelope/transaction metadata in contract_signatures.signature_meta or a dedicated field in contract_instances.
      • Set status='awaiting_signature'.
      • Return minimal status info to the client.

You may simulate e-sign integration with a local stub that pretends the document was sent and will be signed shortly.

2.5 Handle signature callback

Expose a webhook endpoint such as:

  • POST /api/hr/contracts/signature_webhook

This is called by the e-sign provider (or your stub) when a signer completes their part.

Behaviour:

  1. Map the callback payload back to a contract_id.
  2. Insert a row into contract_signatures:
    • contract_id,
    • signer_role (employee or employer_rep),
    • signer_id (if known),
    • signature_meta (raw payload).
  3. Check if all required signatures are present for this contract.
  4. When complete:
    • Set contract_instances.status='active'.
    • Set rendered_pdf_url (location of stored final document).
    • Decide orientation_type:
      • If COUNT(*) of contract_instances for this staff is 1 → new_staff.
      • Else → continuation.
    • Trigger orientation generation (below).
    • Notify DataHub (see 2.7).

2.6 Orientation generation

Create a service function (can be called from the webhook flow) to:

  • Build and send an orientation email.
  • Store it in contract_orientation_payloads.

New staff orientation

  • Triggered when orientation_type = 'new_staff'.
  • Inputs to LLM:
    • staff name,
    • position, hours, and employment type,
    • key points from the contract template,
    • links to key policies (e.g. Code of Conduct, Values, Privacy).
  • Output:
    • HTML email body that:
      • welcomes the staff member,
      • summarises expectations,
      • highlights support available,
      • links to relevant policies/resources.
  • Store:
    • summary_email_html – exact body,
    • llm_notes – optional JSON summarising main sections.
  • Send via our email infrastructure (or stub for now).

Continuation orientation

  • Triggered when orientation_type = 'continuation'.
  • Inputs to LLM:
    • staff name,
    • what changed in this contract (if known),
    • high-level summary of recent performance (for now, you can pass static text or a stub; later this will come from the performance/Annual Development module).
  • Output:
    • HTML email that:
      • acknowledges and praises specific achievements,
      • identifies 2–3 focus areas for improvement,
      • emphasises ongoing support and where to get help.
  • Store and send as above.

2.7 DataHub integration hook

Define a function that is called whenever a contract becomes active:

async function notifyDatahubOfActiveContract(contractInstance, staff, signatures) {
// Example payload shape:
// {
// boardKey: "HR_STAFF_CONTRACTS",
// staffId: staff.id,
// staffName: staff.full_name,
// contractId: contractInstance.id,
// issuedDate: contractInstance.created_at,
// signedDate: <latest signature date>,
// renewalReminderDate: <derived from effective_to or config>,
// expiryDate: contractInstance.effective_to,
// contractFileUrl: contractInstance.rendered_pdf_url
// }
}

For this task, you can either:

  • Call a placeholder DataHub API endpoint, or
  • Just log the payload and leave implementation to a later task.

The important part is that the hook and payload shape exist so we can wire it up.


3. Frontend: Template Management

Create admin UI under the HR section.

3.1 Templates index page

Page: hr_contract_templates.html

  • Table columns:
    • Key,
    • Title,
    • Version,
    • Active?,
    • Created at.
  • Row actions:
    • Edit,
    • Duplicate (clone with new key or incremented version),
    • Toggle Active.

Filter/search by key/title.

3.2 Template editor page

When editing or creating a template:

  • Fields:

    • Key (readonly after creation),
    • Title,
    • Version,
    • Active flag,
    • Body template textarea (large),
    • Clause blocks editor (minimal JSON or simple per-block fields).
  • Show a help sidebar listing available placeholders, e.g.:

    • {{staff_name}}
    • {{position_title}}
    • {{hours_per_fortnight}}
    • {{employment_type}}
    • {{schads_level}}

Save via the template endpoints.


4. Frontend: Staff Contract Wizard

On the staff detail page, add a Contracts tab.

4.1 Contracts tab layout

  • Top section: history table.
    • Columns:
      • Effective from,
      • Effective to,
      • Template title,
      • Status,
      • Orientation type,
      • Link to PDF (if rendered_pdf_url exists).
  • Bottom section:
    • Button: “Generate new contract”.

4.2 Generate contract wizard

When the button is clicked, open a wizard modal (or dedicated page) with:

  1. Step 1 – Choose template
    • Dropdown of active templates.
    • Show title + key.
  2. Step 2 – Set contract details
    • Effective from / to date pickers.
    • Hours per fortnight.
    • Position title.
    • Employment type (select).
    • SCHADS level (select or free-text).
    • Retroactive flag.
  3. Step 3 – Preview
    • Call the generate endpoint.
    • Show rendered contract text in a scrollable area.
    • Allow the user to go back and adjust details if needed.

In Step 3, include:

  • Button: “Send for signature”:
    • Calls send_for_signature endpoint.
    • On success, updates history row with status='awaiting_signature'.

4.3 Refresh and status display

Until a push mechanism is available, include a simple “Refresh” button on the Contracts tab that re-calls the GET /api/hr/staff/:staffId/contracts endpoint and updates the table.

When a contract becomes active:

  • Show a coloured status badge.
  • Show link to the signed PDF.
  • Show “View orientation email” action that opens a modal displaying summary_email_html.

5. LLM Prompts & Safety

For templates and contracts:

  • Treat contract_templates.body_template as legally authoritative text.
  • The LLM should not change core legal clauses unless explicitly requested by an authorised admin in a controlled context.

For orientation emails:

  • Ensure the tone is supportive, clear, and realistic.
  • Avoid promises or guarantees that contradict contracts or policies.

Keep a simple log (even if only server-side logging) of:

  • which prompts were sent,
  • to which contracts they related,
  • a checksum or snippet of responses,

so issues can be debugged later.

End of task.