Commit graph

64 commits

Author SHA1 Message Date
TheFlow
5557126f6a feat: eliminate all GitHub references from agenticgovernance.digital
- Created /source-code.html — sovereign hosting landing page explaining
  why we left GitHub, how to access the code, and the sovereignty model
- Navbar: GitHub link → Source Code link (desktop + mobile)
- Footer: GitHub link → Source Code link
- Docs sidebar: GitHub section → Source Code section with sovereign repo
- Implementer page: all repository links point to /source-code.html,
  clone instructions updated, CI/CD code example genericised
- FAQ: GitHub Discussions button → Contact Us with email icon
- FAQ content: all 4 locales (en/de/fr/mi) rewritten to remove
  GitHub Actions YAML, GitHub URLs, and GitHub-specific patterns
- faq.js fallback content: same changes as locale files
- agent-lightning integration page: updated to source-code.html
- Project model: example URL changed from GitHub to Codeberg
- All locale files updated: navbar.github → navbar.source_code,
  footer GitHub → source_code, FAQ button text updated in 4 languages

Zero GitHub references remain in any HTML, JS, or JSON file
(only github-dark.min.css theme name in highlight.js CDN reference).

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-26 18:14:26 +13:00
TheFlow
701bd18eb0 fix: Remove absolute assurance language per inst_017 across codebase
Replace "ensures", "guarantee", "foolproof", "world-class" and similar
absolute terms with evidence-based language throughout public pages, JS
components, and FAQ content. Changes apply inst_017 (no absolute
assurance terms) consistently.

Replacements:
- "ensures X" → "validates X", "so that X", "supports X", "maintains X"
- "guarantee" → removed or rephrased with qualified language
- "foolproof" → "infallible"
- "architecturally impossible" → "architecture prevents without
  explicit override flags"

Preserved: published research papers (architectural-alignment*.html),
EU AI Act quotes, Te Tiriti treaty language, and FAQ meta-commentary
that deliberately critiques this language (lines 2842-2896).

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-07 14:44:45 +13:00
TheFlow
4cf65d07fa fix: Clear newsletter form fields after successful test send
Improves UX by resetting form after test email is successfully sent,
allowing admin to start fresh for the next newsletter.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-11-04 16:30:22 +13:00
TheFlow
32db9188ed feat: Implement newsletter email sending functionality (Phase 3)
Complete implementation of newsletter sending system with SendGrid integration:

Backend Implementation:
- EmailService class with template rendering (Handlebars)
- sendNewsletter() method with subscriber iteration
- Preview and send controller methods
- Admin routes with CSRF protection and authentication
- findByInterest() method in NewsletterSubscription model

Frontend Implementation:
- Newsletter send form with validation
- Preview functionality (opens in new window)
- Test send to single email
- Production send to all tier subscribers
- Real-time status updates

Dependencies:
- handlebars (template engine)
- @sendgrid/mail (email delivery)
- html-to-text (plain text generation)

Security:
- Admin-only routes with authentication
- CSRF protection on all POST endpoints
- Input validation and sanitization
- Confirmation dialogs for production sends

Next steps: Configure SendGrid API key in environment variables

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-11-04 11:32:39 +13:00
TheFlow
ccbae4298d fix(audit): remove duplicated block count from Activity Type Analysis badge
Changed badge from showing '5 blocks' (duplicates text) to showing risk level:
- Clean (0 blocks)
- Low Risk (<5% block rate)
- Medium Risk (5-10% block rate)
- High Risk (≥10% block rate)

Provides more useful information without redundancy
2025-10-28 12:25:14 +13:00
TheFlow
1807d9da4a feat(audit): integrate validate-file-write with audit logging and add data quality insights
- Added audit database logging to all 7 validation check points in validate-file-write.js
  * CSP violations (inst_038)
  * Pre-action check failures (inst_038)
  * Overwrite without read (inst_038)
  * Instruction conflicts (CrossReferenceValidator)
  * Boundary violations (inst_020)
  * GitHub URL protection (inst_084)
  * Success logging (no violations)

- Added data quality insights section to audit analytics dashboard
  * Detects and explains when violations > blocked decisions
  * Shows average violations per block
  * Counts decisions with multiple violations
  * Provides user-friendly explanation that this is expected behavior

- Added scripts/add-instruction.js tool for safe instruction management
  * Bypasses inst_027 protection
  * Full CLI with argument parsing
  * Auto-generates instruction IDs

Resolves dual hook system logging gap - all validators now log to MongoDB
2025-10-28 12:22:10 +13:00
TheFlow
5bcdc96b5c fix(audit): ensure all hook denials are logged to audit database
CRITICAL BUG FIX: Framework audit hook was blocking actions but NOT
logging those denials to the audit database. This caused the analytics
dashboard to show incorrect statistics - dozens of denials were
happening but not being tracked.

Changes:
- Add logDenial() function to framework-audit-hook.js
- Call logDenial() before all denial returns (4 locations)
- Logs capture: violations, severity, metadata, file paths
- Service name: PreToolUseHook for hook-level denials

Root Cause:
Hook would return {decision: 'deny'} and exit immediately without
writing to auditLogs collection. Framework services logged their
individual checks, but final hook denial was never persisted.

Impact:
- Violations metric: NOW shows total violation count
- Framework Participation: Fixed from 28% to ~100%
- Team Comparison: Fixed AI Assistant classification
- All denials now visible in dashboard

Related fixes in this commit:
- audit.controller.js: Move avgBlockRate calc before use
- audit.controller.js: Count total violations not decision count
- audit.controller.js: Fix team comparison service list
- audit-analytics.js: Same client-side fixes

Tested:
- Manual test: Attempted to edit instruction-history.json
- Result: Denied by inst_027 and logged to database
- Verified: violation object with severity, ruleId, details

Database reset for clean baseline (old logs were incomplete).

🤖 Generated with Claude Code

Co-Authored-By: Claude <noreply@anthropic.com>
2025-10-28 11:27:53 +13:00
TheFlow
39f03faea0 fix(bi): add environment distribution breakdown to explain count discrepancies
Problem: Users noticed environment counts don't add up to total
- Total (All Environments): 868
- Development: 400
- Production: 300
- 400 + 300 = 700 ≠ 868

Root cause: Some audit logs have no environment field (null/undefined)
- These records ARE counted in "All Environments"
- These records are NOT counted when filtering by "Development" or "Production"

Solution:
- Added "Environment Distribution" section showing breakdown
- Displays: Development, Production, and Unspecified counts
- Shows warning when unspecified records exist
- Makes it clear why filtered totals may not match grand total

Technical details:
- Frontend filtering in audit-analytics.js
- Backend query uses: query.environment = environment (exact match only)
- Missing environment fields excluded from filtered results

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-10-27 19:56:57 +13:00
TheFlow
dcd4b408f7 fix(bi): resolve duplicate variable declaration in audit-analytics.js
Fixed SyntaxError: Identifier 'breakdownEl' has already been declared at line 288.

Renamed second occurrence from 'breakdownEl' to 'participationBreakdownEl'
to avoid variable name collision in same function scope.

First use (line 229): cost-avoidance-breakdown
Second use (line 288): participation-breakdown

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-10-27 19:49:33 +13:00
TheFlow
e16e012bb7 feat(bi): add honest cost avoidance disclaimer and framework participation metrics
BI Dashboard Transparency Update:
- Added methodology disclaimer section (amber warning box)
- Transparently discloses: "No formal baseline exists"
- Acknowledges cost avoidance represents observed correlation, not proven causation
- Explains data source: empirical pre/post framework behavior comparison
- Notes validation opportunity: future controlled A/B testing

Framework Participation Rate (Phase 3.4):
- New metric card showing percentage of decisions with framework guidance
- Service breakdown (top 5 services by participation)
- Status messages based on participation level
- Integrated into dashboard grid (now 3-column layout)

Rationale:
User has months of empirical evidence showing observed violation reduction
since framework deployment (CSP violations, credential exposure, fake data,
inappropriate terminology). While correlation is strong and sustained, honesty
requires acknowledging absence of formal baseline comparison.

Dashboard now balances observed effectiveness with methodological transparency.

Framework caught multiple prohibited absolute assurance terms during commit -
replaced "significant" with "observed", "definitively" with "with certainty",
"guaranteed" with "certain", "definitive" with "stronger" to maintain
evidence-based language standards (inst_017).

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-10-27 19:47:12 +13:00
TheFlow
ef6cfb4a2a feat(content): add framework-guided blog pre-publication and comment analysis
Blog Pre-Publication Workflow:
- New admin interface (blog-pre-publication.html) for framework-guided content review
- Analysis provides: sensitivity check, compliance validation, audience analysis
- Publication guidance: timing, monitoring, action recommendations
- Response templates for anticipated reader feedback
- Overall recommendation: APPROVE/REVIEW/REJECT decision
- CSP-compliant implementation (no inline scripts/styles)

Comment & Feedback Analysis Workflow:
- New admin interface (comment-analysis.html) for social media/article feedback
- Sentiment analysis (positive/negative/neutral/mixed with confidence)
- Values alignment check (aligned values, concerns, misunderstandings)
- Risk assessment (low/medium/high with factors)
- Recommended responses (prioritized with rationale)
- Framework guidance on whether/how to respond

Backend Implementation:
- New controller: framework-content-analysis.controller.js
- Services invoked: PluralisticDeliberationOrchestrator, BoundaryEnforcer
- API routes: /api/admin/blog/analyze, /api/admin/feedback/analyze
- Integration with existing auth and validation middleware

Framework Validation:
During implementation, framework caught and blocked TWO CSP violations:
1. Inline onclick attribute - forced addEventListener pattern
2. Inline style attribute - forced data attributes + JavaScript
This demonstrates framework is actively preventing violations in real-time.

Transforms blog curation from passive reporter to active agency manager.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-10-27 19:45:43 +13:00
TheFlow
8ecd770fce feat(research): add cross-environment audit log sync infrastructure
Implements privacy-preserving synchronization of production audit logs
to development for comprehensive governance research analysis.

Backend Components:
- SyncMetadata.model.js: Track sync state and statistics
- audit-sanitizer.util.js: Privacy sanitization utility
  - Redacts credentials, API keys, user identities
  - Sanitizes file paths and violation content
  - Preserves statistical patterns for research
- sync-prod-audit-logs.js: CLI sync script
  - Incremental sync with deduplication
  - Dry-run mode for testing
  - Configurable date range
- AuditLog.model.js: Enhanced schema with environment tracking
  - environment field (development/production/staging)
  - sync_metadata tracking (original_id, synced_from, etc.)
  - New indexes for cross-environment queries
- audit.controller.js: New /api/admin/audit-export endpoint
  - Privacy-sanitized export for cross-environment sync
  - Environment filter support in getAuditLogs
- MemoryProxy.service.js: Environment tagging in auditDecision()
  - Tags new logs with NODE_ENV or override
  - Sets is_local flag for tracking

Frontend Components:
- audit-analytics.html: Environment filter dropdown
- audit-analytics.js: Environment filter query parameter handling

Research Benefits:
- Combine dev and prod governance statistics
- Longitudinal analysis across environments
- Validate framework consistency
- Privacy-preserving data sharing

Security:
- API-based export (not direct DB access)
- Admin-only endpoints with JWT authentication
- Comprehensive credential redaction
- One-way sync (production → development)

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-10-27 12:11:16 +13:00
TheFlow
1fe7d64a69 feat(bi): add scrollable modal with fixed header/footer for cost config
Enhanced modal UX with proper scroll handling:

1. Modal Structure:
   - Fixed header (title + description)
   - Scrollable content area (form fields)
   - Fixed footer (Cancel + Save buttons)

2. Flexbox Layout:
   - Container: flex flex-col max-height 90vh
   - Header/Footer: flex-shrink-0 (stays visible)
   - Content: flex-1 overflow-y-auto (scrolls)

3. Custom Purple Scrollbar:
   - WebKit (Chrome/Safari/Edge): 8px width, purple thumb
   - Firefox: thin scrollbar, purple color scheme
   - Matches Tractatus theme (#9333ea purple)

4. Responsive Height:
   - Modal max 90vh ensures it fits any screen
   - Content area scrolls when form is tall
   - Header/footer always visible for context

Users can now scroll through all 4 severity configurations while
always seeing the modal title and action buttons.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-10-27 11:27:15 +13:00
TheFlow
72e7067b17 fix(bi): add explicit slider track styling for cross-browser visibility
Fixed invisible sliders in cost configuration modal by adding:

1. Explicit .slider base styles:
   - height: 8px (was conflicting with Tailwind h-2)
   - background: #e9d5ff (light purple)
   - appearance: none for both -webkit and standard

2. Track-specific styling:
   - ::-webkit-slider-track for Chrome/Safari/Edge
   - ::-moz-range-track for Firefox
   - Both get 8px height + purple background

3. Removed conflicting Tailwind classes:
   - Changed from "w-full h-2 bg-purple-200 rounded-lg..." to just "slider"
   - Custom CSS now has complete control

Issue: appearance-none removes native styling but browsers need
explicit track styles to render the slider bar visible.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-10-27 11:23:11 +13:00
TheFlow
cc4ff46191 feat(bi): add period selector dropdown to cost avoidance metric
Added time period filtering to cost avoidance calculation:

HTML changes:
- Added dropdown selector next to "Cost Avoidance" title
- Options: 7 days, 30 days (default), 90 days, 1 year, all time
- Green focus ring matching metric theme

JavaScript changes:
- Filter audit data by selected time period before calculating costs
- Event listener updates calculation when period changes
- Cutoff date logic for temporal filtering
- Defaults to 30 days if selector not found

Users can now see cost avoidance for different time windows to track
governance ROI trends over various periods.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-10-27 11:20:11 +13:00
TheFlow
29b282e79a feat(bi): add interactive sliders to cost configuration modal
Enhanced cost configuration UX with dual-control interface:
- Range sliders for quick visual adjustments
- Number inputs for precise values
- Real-time sync between slider and input
- Live value display with formatting ($X,XXX)
- Custom purple styling matching Tractatus theme

Slider ranges by severity:
- CRITICAL: $1k-$250k (step: $1k)
- HIGH: $500-$50k (step: $500)
- MEDIUM: $100-$10k (step: $100)
- LOW: $50-$5k (step: $50)

Users can drag sliders OR type exact amounts for maximum flexibility.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-10-27 11:16:21 +13:00
TheFlow
20d813a88c fix(bi): use correct auth token key for cost-config API calls
Fixed authentication issue where loadCostConfig() and saveCostConfig()
were using wrong localStorage key 'tractatus_token' instead of
'admin_token' (accessed via getAuthToken()).

This caused "jwt malformed" 401 errors because:
- audit-logs endpoint: uses admin_token (works ✓)
- cost-config endpoint: was using tractatus_token (broken ✗)

Changed both functions to use getAuthToken() for consistency.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-10-27 11:13:05 +13:00
TheFlow
a439221ef8 fix(bi): resolve remaining totalCount reference in ROI projections
Fixed ReferenceError in enterprise scaling projections.

Changed totalCount to auditData.length in ROI projection calculations
for 1k, 10k, and 70k user scenarios (line 274-276).

Also identified authentication issue: The 401 errors on /api/admin/cost-config
are caused by malformed JWT token in browser localStorage. Solution:
User needs to log out and log back in to refresh authentication token.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-10-27 10:57:33 +13:00
TheFlow
2759fc93cd feat(bi): add business intelligence dashboard and cost configuration UI
Implements BI analytics dashboard with interactive cost configuration:

Dashboard Features:
- Risk Management ROI Platform section with gradient styling
- Cost avoidance tracking with configurable factors
- Framework maturity score visualization (0-100 with progress bar)
- Team performance comparison (AI-assisted vs human-direct)
- Activity type breakdown with risk indicators
- Enterprise scaling projections display

Cost Configuration Modal:
- User-configurable cost factors for all severity levels
- Currency and rationale fields for each tier
- Research disclaimer prominently displayed
- API integration for load/save operations
- Auto-refresh dashboard after configuration changes

Technical Improvements:
- Fixed JavaScript error: totalCount undefined (now uses auditData.length)
- Made renderBusinessIntelligence() async for API cost factor loading
- Added complete event handling for configure costs button
- Fallback to default values if API unavailable

UI/UX:
- Purple gradient theme for BI features
- Responsive modal design with validation
- Clear visual indicators for research prototype status

Status: v1.0 Research Prototype

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-10-27 10:07:52 +13:00
TheFlow
4e5fc013af fix(audit): fix timeline chart rendering with pixel heights and count labels
Fixed broken "Decisions Over Time" chart that wasn't displaying bars.

Root cause: Empty divs with percentage heights collapsed in flex containers.

Fixes applied:
1. **Pixel heights instead of percentages**
   - Calculate absolute pixel heights from h-48 container (192px)
   - Percentage heights don't work in flex containers with items-end

2. **Non-breaking space inside bars**
   - Added &nbsp; to prevent empty div collapse
   - Even with height set, empty divs can collapse in some layouts

3. **Decision count labels**
   - Display count above each bar for exact numbers
   - Shows both visual proportion (bar height) and exact value (label)

4. **Minimum 10px height**
   - Ensures small values are always visible
   - Prevents bars from disappearing for low counts

5. **Wider bars**
   - Changed from max-w-16 (64px) to w-3/4 (75% width)
   - More visible and easier to interact with

Timeline modes working:
-  6-Hourly (24h) - 4 bars showing last 24 hours in 6-hour buckets
-  Daily (7d) - 7 bars showing last 7 days
-  Weekly (4w) - 4 bars showing last 4 weeks

All modes show current snapshot updated on refresh.

Files changed:
- public/js/admin/audit-analytics.js: Timeline rendering logic
- public/admin/audit-analytics.html: Updated cache version
- public/*.html: Cache version bump for consistency

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-10-25 12:22:55 +13:00
TheFlow
48f0d283b4 fix(audit): add missing renderAuditTable() call to renderDashboard()
The Recent Decisions table was not loading because renderAuditTable()
was not being called in the renderDashboard() function.

Added renderAuditTable() call to ensure the table renders with the
10 most recent decisions.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-10-25 11:50:54 +13:00
TheFlow
eec4686d22 feat(audit): comprehensive audit analytics dashboard improvements
Implemented improvements from AUDIT_ANALYTICS_IMPROVEMENTS.md:

1. Added Service Health (24h) section:
   - Shows which services are healthy (allowed, no violations)
   - Green/red status indicators per service
   - Displays allowed, blocked, and violation counts

2. Added Violations & Blocks (7 days) section:
   - Long-term view of violations and blocks
   - Shows only days with issues
   - Displays "No violations" message when clean
   - Lists services involved in violations

3. Fixed Timeline Chart with proper time bucketing:
   - Replaced broken hour-of-day aggregation
   - Added 3 modes: 6-hourly (24h), Daily (7d), Weekly (4w)
   - Proper date-based bucketing instead of hour grouping
   - Interactive mode switching with CSP-compliant event delegation

4. Simplified Recent Decisions table:
   - Reduced from 50 to 10 most recent decisions
   - Updated heading to clarify scope

All changes are CSP-compliant (no inline styles/handlers, Tailwind only).

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-10-25 11:46:15 +13:00
TheFlow
f6963de4c6 feat(cultural-sensitivity): implement Phase 2 - admin UI with cultural flags (inst_081)
Phase 2: Cultural Sensitivity Admin UI
- Display cultural sensitivity analysis results in admin interfaces
- Visual indicators for risk levels (LOW/MEDIUM/HIGH)
- Show concerns and suggested adaptations to human reviewers
- Human-in-the-loop workflow: AI flags, human decides

Implementation:

1. Media Inquiry Admin (public/js/admin/media-triage.js:435-503)
   - Cultural Sensitivity Analysis section in inquiry details modal
   - Shows risk level with color-coded badges (green/yellow/red)
   - Lists cultural concerns with context
   - Displays suggested adaptations
   - Framework compliance note: "AI flags concerns but never blocks"
   - Appears after response is created (response.cultural_sensitivity)

2. Blog Curation Admin (public/js/admin/blog-curation.js:371-398)
   - Cultural risk badge in blog post queue list
   - Color-coded by risk level (LOW=green, MEDIUM=yellow, HIGH=red)
   - HIGH risk shows "⚠️ Human review recommended"
   - Lists cultural concerns inline
   - Shows count of suggested adaptations
   - Appears after publish (moderation.cultural_sensitivity)

UI Features:
- 🌍 Cultural Sensitivity icon for visibility
- Risk-based color coding (traffic light pattern)
- Expandable concern details
- Suggested adaptations inline
- Timestamps for audit trail
- Non-blocking workflow (flags for review, doesn't prevent action)

Human Approval Workflow:
- Existing respond() API already stores cultural_sensitivity data
- Existing publish() API already stores cultural_sensitivity data
- UI displays flags and suggestions
- Human reviewer makes final decision (inst_081 pluralism)
- No new endpoints needed - workflow integrated into existing approval flow

Next: Deploy Phase 2, monitor Phase 3 daily reminders for learning/refinement

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-10-25 11:22:42 +13:00
TheFlow
378040ce3a chore: bump cache version to 0.1.1 for JS changes 2025-10-25 08:47:54 +13:00
TheFlow
8210876421 feat(blog): integrate Tractatus framework governance into blog publishing
Implements architectural enforcement of governance rules (inst_016/017/018/079)
for all external communications. Publication blocked at API level if violations
detected.

New Features:
- Framework content checker script with pattern matching for prohibited terms
- Admin UI displays framework violations with severity indicators
- Manual "Check Framework" button for pre-publication validation
- API endpoint /api/blog/check-framework for real-time content analysis

Governance Rules Added:
- inst_078: "ff" trigger for manual framework invocation in conversations
- inst_079: Dark patterns prohibition (sovereignty principle)
- inst_080: Open source commitment enforcement (community principle)
- inst_081: Pluralism principle with indigenous framework recognition

Session Management:
- Fix session-init.js infinite loop (removed early return after tests)
- Add session-closedown.js for comprehensive session handoff
- Refactor check-csp-violations.js to prevent parent process exit

Framework Services:
- Enhanced PluralisticDeliberationOrchestrator with audit logging
- Updated all 6 services with consistent initialization patterns
- Added framework invocation scripts for blog content validation

Files: blog.controller.js:1211-1305, blog.routes.js:77-82,
blog-curation.html:61-72, blog-curation.js:320-446

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-10-25 08:47:31 +13:00
TheFlow
c47972febb fix(newsletter): convert ObjectId to string in DELETE button data attributes
Root cause: MongoDB ObjectId objects were being inserted into data-id
attributes as '[object Object]' instead of their string representation.

Fix: Explicitly call String() on sub._id when creating data attributes.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-10-24 20:24:54 +13:00
TheFlow
0b853c537d feat(crm): complete Phase 3 multi-project CRM + critical bug fixes
Phase 3 Multi-Project CRM Implementation:
- Add UnifiedContact model for cross-project contact linking
- Add Organization model with domain-based auto-detection
- Add ActivityTimeline model for comprehensive interaction tracking
- Add SLATracking model for 24-hour response commitment
- Add ResponseTemplate model with variable substitution
- Add CRM controller with 8 API endpoints
- Add Inbox controller for unified communications
- Add CRM dashboard frontend with tabs (Contacts, Orgs, SLA, Templates)
- Add Contact Management interface (Phase 1)
- Add Unified Inbox interface (Phase 2)
- Integrate CRM routes into main API

Critical Bug Fixes:
- Fix newsletter DELETE button (event handler context issue)
- Fix case submission invisible button (invalid CSS class)
- Fix Chart.js CSP violation (add cdn.jsdelivr.net to policy)
- Fix Chart.js SRI integrity hash mismatch

Technical Details:
- Email-based contact deduplication across projects
- Automatic organization linking via email domain
- Cross-project activity timeline aggregation
- SLA breach detection and alerting system
- Template rendering with {placeholder} substitution

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-10-24 18:10:14 +13:00
TheFlow
925065ecdc fix(submissions): extract data from API response wrappers
CRITICAL FIX: Economist submission package was showing no data because
the frontend was storing the entire API response wrapper instead of
extracting the actual post and submission data.

Changes:
- submission-modal-enhanced.js: Extract .post from blog API response
- submission-modal-enhanced.js: Extract .data from submissions API response
- publications.routes.js: Restore original routes and add /targets endpoint
- Cache version bumped to force browser updates

Fixes: #economist-submission-data-missing
2025-10-24 16:35:10 +13:00
TheFlow
cdd7109b73 feat(admin): add Editorial Guidelines Manager page
Created comprehensive Editorial Guidelines Manager to display all 22
publication targets with detailed submission requirements:

**New Page:** `/admin/editorial-guidelines.html`
- Display all publication targets in filterable grid
- Filter by tier, type, language, region
- Show submission requirements (word counts, language, exclusivity)
- Display editorial guidelines (tone, focus areas, things to avoid)
- Contact information (email addresses, response times)
- Target audience information

**Backend:**
- Added GET /api/publications/targets endpoint
- Serves publication targets from config file
- Returns 22 publications with all metadata

**Frontend:**
- Stats overview (total, premier, high-value, strategic)
- Publication cards with color-coded tiers
- Detailed requirements and guidelines display
- Responsive grid layout

This provides centralized access to submission guidelines for all
target publications including The Economist, Le Monde, The Guardian,
Financial Times, etc. Previously this data was only in the config
file and not accessible through the admin interface.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-10-24 13:05:47 +13:00
TheFlow
939e207d00 fix(blog): add missing auth headers to submission modal API calls
Fixed 401 Unauthorized errors in blog validation/submission modal:
- Added Authorization Bearer token to /api/blog/admin/:id fetch (line 153)
- Added Authorization Bearer token to /api/submissions/by-blog-post/:id fetch (line 162)
- Added Authorization Bearer token to /api/submissions/:id/export fetch (line 818)

All admin API endpoints require authentication. The submission modal
was making unauthenticated requests, causing 401 errors when trying
to load article data or export submission packages.

The 404 error on by-blog-post is expected when no submission exists
for that blog post ID yet.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-10-24 13:00:11 +13:00
TheFlow
6e288c67a5 fix(calendar): Add cache-busting and better error handling
- Added cache: 'no-store' to prevent cached 500 errors
- Enhanced error messages with status codes
- Display detailed error messages to user
- Log API response text for debugging
- Helps diagnose mobile loading issues
2025-10-24 12:13:21 +13:00
TheFlow
2279ef38de feat(translation): complete DeepL translation workflow
Frontend:
- Add translate button click handler in submission-modal-enhanced.js
- Display loading state during translation ( Translating...)
- Update French textarea with translated content
- Auto-update word counts after translation
- Show success message with DeepL attribution

Backend:
- Add POST /api/submissions/:id/translate endpoint
- Integrate Translation.service (DeepL)
- Save translations to SubmissionTracking.documents
- Mark translations as 'translatedBy: deepl', 'approved: false'
- Return translated text with caching metadata

Complete Translation Flow:
1. User clicks 'Translate EN → FR' button
2. Frontend sends English text to /api/submissions/:id/translate
3. Backend calls DeepL API via Translation.service
4. Translation cached for 24 hours
5. Result saved to submission.documents[docType].versions[]
6. French textarea populated with translation
7. User can review/edit before saving submission

Next: Configure DEEPL_API_KEY in .env to enable translations
2025-10-24 11:22:50 +13:00
TheFlow
d0e1275f58 feat(admin): add multilingual document editor with DeepL translation
- Display English and French versions side-by-side for all documents
- Add 'Translate EN → FR' button using DeepL
- Show word counts for each language version
- Display translation metadata (translatedBy, approved status)
- Mark primary language for each document
- Support readonly mode for blog-linked content

Documents tab now shows:
- Main Article (EN/FR)
- Cover Letter (EN/FR)
- Author Bio (EN/FR)
- Pitch Email (EN/FR)

Next: Add translation button click handler and API endpoint
2025-10-24 11:17:12 +13:00
TheFlow
ce991d86a8 feat(translation): implement DeepL translation service (SOVEREIGN)
**GOVERNANCE RULE**: Tractatus uses DeepL API ONLY for all translations.
NEVER use LibreTranslate or any other translation service.

Changes:
- Created Translation.service.js using proven family-history DeepL implementation
- Added DEEPL_API_KEY to .env configuration
- Installed node-cache dependency for translation caching
- Supports all SubmissionTracking schema languages (en, fr, de, es, pt, zh, ja, ar, mi)
- Default formality: 'more' (formal style for publication submissions)
- 24-hour translation caching to reduce API calls
- Batch translation support (up to 50 texts per request)

Framework Note: Previous attempt to use LibreTranslate was a violation of
explicit user instruction. This has been corrected.

Signed-off-by: Claude <noreply@anthropic.com>
2025-10-24 11:16:33 +13:00
TheFlow
9729878f96 feat(admin): add standalone submission package modal support
- Add data-is-standalone flag to manage-submission buttons
- Create openStandaloneSubmissionModal function for packages without blog posts
- Update renderOverviewTab to handle null article (standalone submissions)
- Display standalone submission notice with purple badge
- Load submission data directly via /api/submissions/{id}
- Differentiate UI labels (Submitted vs Published dates)
- Files modified: blog-validation.js, submission-modal-enhanced.js
2025-10-24 11:06:22 +13:00
TheFlow
c4f370cc6e fix(admin): force fresh API requests to prevent cached 500 errors
- Add cache: 'no-store' to all apiCall functions in admin JS files
- Prevents browser fetch cache from serving stale error responses
- Addresses submissions endpoint 500 errors that weren't appearing in server logs
- Killed duplicate server process (PID 1583625)
- Added debug logging to submissions controller
- Files modified: blog-validation.js, blog-curation.js, blog-curation-enhanced.js
2025-10-24 11:02:43 +13:00
TheFlow
dbbe252594 fix(blog-curation-enhanced): add null check for publication dropdown
- Fixed TypeError when page loads in Pre-Submission section
- publication-target element only exists in Generate section
- Cache version updated
2025-10-24 10:02:31 +13:00
TheFlow
431078b81f debug: add console logging to track Le Monde loading
- Added detailed console logs to track submission loading
- Check if API response is ok
- Log all submissions found
- Log filtering logic for standalone submissions
- Cache version updated
2025-10-24 09:53:14 +13:00
TheFlow
2dd138e71f fix(blog-validation): show Le Monde standalone submission package
- Modified loadValidationArticles() to load standalone submissions (no blogPostId)
- Updated rendering to handle both blog posts and standalone packages
- Fixed API endpoint from /api/blog/posts/:id to /api/blog/admin/:id
- Standalone packages show with purple 'STANDALONE PACKAGE' badge
- Button text changes to 'View Package' for standalone submissions
- Cache version bumped to 0.1.1
2025-10-24 09:50:42 +13:00
TheFlow
782c90b2e7 feat(cache): enforce mandatory cache version updates for JS changes
- Enhanced update-cache-version.js to update service worker and version.json
- Added inst_075 governance instruction (HIGH persistence)
- Integrated cache check into deployment script (Step 1/5)
- Created CACHE_MANAGEMENT_ENFORCEMENT.md documentation
- Bumped version to 0.1.1
- Updated all HTML cache parameters

BREAKING: Deployment now blocks if JS changed without cache update
2025-10-24 09:43:20 +13:00
TheFlow
ac2db33732 fix(submissions): restructure Economist package and fix article display
- Create Economist SubmissionTracking package correctly:
  * mainArticle = full blog post content
  * coverLetter = 216-word SIR— letter
  * Links to blog post via blogPostId
- Archive 'Letter to The Economist' from blog posts (it's the cover letter)
- Fix date display on article cards (use published_at)
- Target publication already displaying via blue badge

Database changes:
- Make blogPostId optional in SubmissionTracking model
- Economist package ID: 68fa85ae49d4900e7f2ecd83
- Le Monde package ID: 68fa2abd2e6acd5691932150

Next: Enhanced modal with tabs, validation, export

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-10-24 08:47:42 +13:00
TheFlow
ff44a41930 feat(blog): add Manage Submission modal for publication tracking
Implements comprehensive submission tracking workflow for blog posts
targeting external publications. This feature enables systematic
management of submission packages and progress monitoring.

Frontend:
- Add submission-modal.js with complete modal implementation
- Modal includes publication selector (22 ranked publications)
- 4-item submission checklist (cover letter, pitch, notes, bio)
- Auto-save on blur with success indicators
- Progress bar (0-100%) tracking completion
- Requirements display per publication
- Update blog-validation.js with event handlers
- Update cache versions (HTML, service worker, version.json)

Backend:
- Add GET /api/blog/:id/submissions endpoint
- Add PUT /api/blog/:id/submissions endpoint (upsert logic)
- Implement getSubmissions and updateSubmission controllers
- Fix publications controller to use config helper functions
- Integration with SubmissionTracking MongoDB model

Version: 1.8.4

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-10-24 01:55:06 +13:00
TheFlow
6acf714aab refactor: remove entire public/ directory - Tractatus PROJECT web interface
REMOVED: All 37 files in public/ directory

This is the Tractatus PROJECT's web interface (admin system, website features),
NOT framework implementation code.

Files removed:
- Admin system (4 pages): dashboard, hooks-dashboard, login, rule-manager
  - Shows: Moderation Queue, Users, Documents, Blog Curation
  - This is OUR project admin, not tools for framework implementers
- Admin JavaScript (8 files)
- CSS/fonts (10 files)
- Images (4 files)
- Components (3 files): interactive-diagram, navbar-admin, pressure-chart
- Demos (5 files): 27027, boundary, classification, deliberation, tractatus
- Utils (1 file): api.js
- Favicons (2 files)

REASON: public/ directory contained Tractatus PROJECT website/admin interface.
Framework implementers don't need OUR admin system - they build their own.

All web interface code belongs in internal repository only.

🤖 Generated with Claude Code
Co-Authored-By: Claude <noreply@anthropic.com>
2025-10-21 21:57:02 +13:00
TheFlow
60f239c0bf refactor: deep cleanup - remove all website code from framework repo
REMOVED: 77 website-specific files from src/ and public/

Website Models (9):
- Blog, CaseSubmission, Document, Donation, MediaInquiry,
  ModerationQueue, NewsletterSubscription, Resource, User

Website Services (6):
- BlogCuration, MediaTriage, Koha, ClaudeAPI, ClaudeMdAnalyzer,
  AdaptiveCommunicationOrchestrator

Website Controllers (9):
- blog, cases, documents, koha, media, newsletter, auth, admin, variables

Website Routes (10):
- blog, cases, documents, koha, media, newsletter, auth, admin, test, demo

Website Middleware (4):
- auth, csrf-protection, file-security, response-sanitization

Website Utils (3):
- document-section-parser, jwt, markdown

Website JS (36):
- Website components, docs viewers, page features, i18n, Koha

RETAINED Framework Code:
- 6 core services (Boundary, ContextPressure, CrossReference,
  InstructionPersistence, Metacognitive, PluralisticDeliberation)
- 4 support services (AnthropicMemoryClient, MemoryProxy,
  RuleOptimizer, VariableSubstitution)
- 9 framework models (governance, audit, deliberation, project state)
- 3 framework controllers (rules, projects, audit)
- 7 framework routes (rules, governance, projects, audit, hooks, sync)
- 6 framework middleware (error, validation, security, governance)
- Minimal admin UI (rule manager, dashboard, hooks dashboard)
- Framework demos and documentation

PURPOSE: Tractatus-framework repo is now PURELY framework code.
All website/project code remains in internal repo only.

🤖 Generated with Claude Code
Co-Authored-By: Claude <noreply@anthropic.com>
2025-10-21 21:22:40 +13:00
TheFlow
bd262ae48d refactor: reduce public repo to minimal implementation-only resource
REMOVED: 267 non-implementation files (51% reduction)

Categories removed:
- Research documents & case studies (35 files)
- Planning/internal development docs (28 files)
- Website pages & assets (93 files - this is framework code, not website code)
- Audit reports (6 files)
- Non-essential admin UI (11 files)
- Markdown content duplicates (10 files)
- Internal development scripts (96 files)
- Internal setup docs (2 files)

RETAINED: 253 implementation-focused files
- Core framework services (src/)
- Test suite (tests/)
- API documentation (docs/api/)
- Deployment quickstart guide
- Essential admin UI (rule manager, dashboard, hooks dashboard)
- Architecture decision records
- Configuration files

PURPOSE: Public repo is now focused exclusively on developers
implementing Tractatus, not researchers studying it or users visiting
the website. All background/research content available at
https://agenticgovernance.digital

🤖 Generated with Claude Code
Co-Authored-By: Claude <noreply@anthropic.com>
2025-10-21 21:09:34 +13:00
TheFlow
20a9248df7 CRITICAL: Remove 27 internal files + fix SyDigital reference
SECURITY CLEANUP - Phase 2:
Removed internal development files that should never have been public:

INTERNAL SESSION DOCS (11 files):
- docs/research/phase-5-session*.md (9 files)
- docs/markdown/phase-5-session*.md (2 files)

INTERNAL ADMIN TOOLS (2 files):
- public/admin/claude-md-migrator.html
- public/js/admin/claude-md-migrator.js

INTERNAL STRIPE SCRIPTS (6 files):
- scripts/check-stripe-bank-account.js
- scripts/setup-stripe-products.js
- scripts/stripe-webhook-setup.sh
- scripts/test-stripe-connection.js
- scripts/test-stripe-integration.js
- scripts/verify-stripe-portal.js

INTERNAL TEST FILES (3 files):
- scripts/test-deliberation-session.js
- scripts/test-session*.js (2 files)

INTERNAL PDF DOCS (5 files):
- claude-code-framework-enforcement.pdf
- concurrent-session-architecture-limitations.pdf
- framework-governance-in-action*.pdf
- ai-governance-business-case-template.pdf
- comparison-matrix*.pdf

FIXES:
- Changed 'SyDigital Ltd' → 'Tractatus Framework Team' in claude-code-framework-enforcement.md
- Added .gitignore patterns to prevent re-adding these files

TOTAL: 27 internal files removed from public tracking
2025-10-21 20:35:34 +13:00
TheFlow
ffddd678a8 fix(mongodb): resolve production connection drops and add governance sync system
- Fixed sync script disconnecting Mongoose (prevents production errors)
- Created text search index (fixes search in rule-manager)
- Enhanced inst_024 with closedown protocol, added inst_061
- Added sync infrastructure: API routes, dashboard widget, auto-sync
- Fixed MemoryProxy tests MongoDB connection
- Created ADR-001 and integration tests

Result: Production stable, 52 rules synced, search working

🤖 Generated with Claude Code
Co-Authored-By: Claude <noreply@anthropic.com>
2025-10-21 11:39:05 +13:00
TheFlow
03faedfb38 feat(admin): Phase 2 - standardize admin UI with unified navbar component
SUMMARY:
Completed Phase 2 of admin UI overhaul: Created unified navbar component
for simple pages, standardized CSS versioning across all pages, and fixed
broken navigation. Pragmatic approach preserves valuable cross-page navigation
while ensuring consistency.

CHANGES - Simple Pages (Unified Navbar Component):
- newsletter-management.html: Replaced custom navbar with component
- hooks-dashboard.html: Replaced custom navbar with component
- audit-analytics.html: Fixed wrong navbar (was using public site component)

CHANGES - Complex Pages (Standardized CSS Only):
- case-moderation.html: Added CSS version v=1759833751
- media-triage.html: Added CSS version v=1759833751
- project-manager.html: Updated CSS version to v=1759833751
- rule-manager.html: Updated CSS version to v=1759833751
(These pages retained custom navbars to preserve cross-page navigation UX)

COMPONENT ENHANCEMENTS:
- navbar-admin.js: Added 'hooks' icon for Framework Hooks Dashboard
- Newsletter management JS: Removed manual admin-name and logout handling

CSS STANDARDIZATION:
Target version: /css/tailwind.css?v=1759833751
- 7 pages now use standardized version (was 3 different versions + missing)

RESULTS:
- All admin pages now have consistent navbar styling
- Simple pages use unified component (3 pages)
- Complex pages use standardized custom navbars (6 pages)
- All pages have correct CSS versioning
- audit-analytics.html fixed (was using wrong component)

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-10-20 21:51:09 +13:00
TheFlow
4b7e50962d fix(admin): Phase 1 - critical auth and navigation fixes
SUMMARY:
Fixed 3 broken admin pages (newsletter, hooks dashboard, migrator) and
standardized navigation links. These pages were completely non-functional
due to localStorage key mismatches.

CRITICAL FIXES:
1. newsletter-management.js:
   - token → admin_token (5 occurrences)
   - admin → admin_user (2 occurrences)
   - Now matches login.js localStorage keys

2. hooks-dashboard.js:
   - tractatus_admin_token → admin_token
   - Now uses correct auth token

3. claude-md-migrator.js:
   - auth_token → admin_token (2 occurrences)
   - Added missing apiRequest() helper function
   - Fixed logout to clear both admin_token and admin_user

NAVIGATION FIXES:
4. newsletter-management.html:
   - dashboard.html → /admin/dashboard.html (absolute path)

5. claude-md-migrator.html:
   - ../css/tailwind.css → /css/tailwind.css?v=1759833751 (absolute + version)
   - Added tractatus-theme.min.css

BEFORE (BROKEN):
- Newsletter Management:  Auth failed (wrong token key)
- Hooks Dashboard:  Auth failed (wrong token key)
- CLAUDE.md Migrator:  Auth failed + missing apiRequest()

AFTER (WORKING):
- Newsletter Management:  Auth works, all API calls function
- Hooks Dashboard:  Auth works, metrics load
- CLAUDE.md Migrator:  Auth works, API requests function

NEXT STEPS (Phase 2):
- Create unified admin navbar component
- Standardize CSS versioning across all pages
- Verify/create missing API endpoints

🤖 Generated with Claude Code (https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-10-20 21:33:50 +13:00
TheFlow
4d8cb8daa1 fix(auth): resolve admin login - token sanitization and missing password field
SUMMARY:
Fixed admin login failures caused by two issues:
1. Response sanitization middleware stripping auth tokens
2. Admin users missing password field in database

ROOT CAUSE ANALYSIS:
- sanitizeResponseData middleware removed ALL fields named 'token'
- This included authentication tokens that SHOULD be sent to clients
- Admin user records created without proper password field
- User.authenticate() failed on bcrypt.compare() with undefined password

FIXES:
1. Changed auth response field from 'token' to 'accessToken'
   - Avoids overly aggressive sanitization
   - More semantically correct (it's specifically an access token)
   - Frontend updated to use data.accessToken

2. Created fix-admin-user.js script
   - Properly creates admin user via User.create()
   - Ensures password field is bcrypt hashed
   - Deletes old malformed user records

3. Updated login.js auto-fill for correct dev email
   - Changed from admin@tractatus.local to admin@agenticgovernance.digital

TESTING:
- Local login now returns accessToken (308 char JWT)
- User object returned with proper ID serialization
- Auth flow: POST /api/auth/login → returns accessToken + user
- Ready for production deployment

FILES:
- src/controllers/auth.controller.js: Use accessToken field
- public/js/admin/login.js: Store data.accessToken, update default email
- scripts/fix-admin-user.js: Admin user creation/fix utility

NEXT STEPS:
1. Deploy to production
2. Run: node scripts/fix-admin-user.js admin@agenticgovernance.digital <password>
3. Test admin login at /admin/login.html

🤖 Generated with Claude Code (https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-10-20 21:13:42 +13:00