feat(corporate): expose persisted execution evidence and QA dossier
Deploy Canina / deploy (push) Successful in 3m56s
Deploy Canina / deploy (push) Successful in 3m56s
This commit is contained in:
1 parent
69dd6922f6
commit
5642c1609c
15 files changed
+369
-6
No files matched your search
@@ -13,7 +13,7 @@
|
||||
"start:debug": "nest start --debug --watch",
|
||||
"start:prod": "node dist/main",
|
||||
"lint": "eslint \"{src,apps,libs,test}/**/*.ts\" --fix",
|
||||
"test": "jest",
|
||||
"test": "python3 scripts/test-postgres.py",
|
||||
"test:watch": "jest --watch",
|
||||
"test:cov": "jest --coverage",
|
||||
"test:debug": "node --inspect-brk -r tsconfig-paths/register -r ts-node/register node_modules/.bin/jest --runInBand",
|
||||
|
||||
@@ -0,0 +1,114 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Run backend tests against freshly initialized, disposable PostgreSQL only.
|
||||
|
||||
Requires Python 3, installed backend dependencies, and PostgreSQL 16+ binaries
|
||||
(initdb, pg_ctl, postgres) on PATH or in PG_BIN. Never reuses a running database.
|
||||
Stage-principal /app + Redis integration tests remain separately opt-in.
|
||||
"""
|
||||
import os
|
||||
from pathlib import Path
|
||||
import shutil
|
||||
import signal
|
||||
import socket
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
|
||||
BACKEND = Path(__file__).resolve().parents[1]
|
||||
|
||||
|
||||
def run(args, env=None):
|
||||
subprocess.run([str(a) for a in args], cwd=BACKEND, env=env, check=True)
|
||||
|
||||
|
||||
def binary(name):
|
||||
candidate = str(Path(os.environ['PG_BIN']) / name) if os.environ.get('PG_BIN') else shutil.which(name)
|
||||
if not candidate or not os.access(candidate, os.X_OK):
|
||||
raise RuntimeError(f'{name} unavailable: install PostgreSQL binaries or set PG_BIN; integration tests cannot be skipped')
|
||||
return candidate
|
||||
|
||||
|
||||
def interrupted(signum, _frame):
|
||||
raise SystemExit(128 + signum)
|
||||
|
||||
|
||||
def main():
|
||||
initdb, pg_ctl = binary('initdb'), binary('pg_ctl')
|
||||
binary('postgres')
|
||||
if os.geteuid() == 0:
|
||||
raise RuntimeError('Run disposable PostgreSQL tests as a non-root user')
|
||||
for sig in (signal.SIGTERM, signal.SIGINT):
|
||||
signal.signal(sig, interrupted)
|
||||
env = os.environ.copy()
|
||||
# Do not propagate operational database URLs to Prisma schema setup or tests.
|
||||
for key in list(env):
|
||||
if key.endswith('DATABASE_URL'):
|
||||
del env[key]
|
||||
env.pop('STAGE_PRINCIPAL_DISPOSABLE_TEST', None)
|
||||
env['DATABASE_URL'] = 'postgresql://disabled@127.0.0.1:1/disabled'
|
||||
definitions = [
|
||||
('SEO_TEST_DATABASE_URL', 'seo_test', 55439, 'postgres', ''),
|
||||
# Keep the existing publication fixture's literal URL allowlist intact.
|
||||
('PUBLICATION_TEST_DATABASE_URL', 'publication_test', 55447, 'publication_test', None),
|
||||
('CORPORATE_TEST_DATABASE_URL', 'corporate_test', 55449, 'corporate_test', ''),
|
||||
]
|
||||
# Refuse occupied dedicated ports before creating any cluster. PostgreSQL's
|
||||
# own bind still protects against races; no existing server is ever stopped.
|
||||
for _, _, port, _, _ in definitions:
|
||||
with socket.socket() as probe:
|
||||
probe.bind(('127.0.0.1', port))
|
||||
started = []
|
||||
with tempfile.TemporaryDirectory(prefix='backend-pg-', dir=os.environ.get('TMPDIR', '/opt/data/cache/scratch')) as root:
|
||||
try:
|
||||
for key, user, port, database, password in definitions:
|
||||
data = Path(root) / str(port)
|
||||
unix_socket = Path(root) / f's{port}'
|
||||
unix_socket.mkdir(mode=0o700)
|
||||
run([initdb, '-D', data, '-U', user, '--auth=trust', '--no-locale', '--encoding=UTF8'])
|
||||
# Track our initialized directory before startup, so even an
|
||||
# interrupted pg_ctl start is cleaned up, never another server.
|
||||
started.append(data)
|
||||
run([pg_ctl, '-D', data, '-l', Path(root) / f'{port}.log', '-w', '-t', '30',
|
||||
'-o', f'-h 127.0.0.1 -p {port} -k {unix_socket}', 'start'])
|
||||
if password is None:
|
||||
# The fixture owns its dedicated test-only credential prefix;
|
||||
# read that literal rather than duplicate or log it here.
|
||||
import re
|
||||
fixture = (BACKEND / 'src/seo-tracking/publication.postgres.spec.ts').read_text()
|
||||
match = re.search(r"url\.startsWith\('([^']+)'\)", fixture)
|
||||
if not match:
|
||||
raise RuntimeError('Publication disposable URL allowlist not found')
|
||||
from urllib.parse import urlsplit
|
||||
prefix = match.group(1)
|
||||
parsed = urlsplit(prefix)
|
||||
if parsed.hostname != '127.0.0.1' or parsed.port != port or parsed.username != user or parsed.path != '/':
|
||||
raise RuntimeError('Publication allowlist is not the dedicated disposable endpoint')
|
||||
url = prefix + database
|
||||
else:
|
||||
url = f'postgresql://{user}{password}@127.0.0.1:{port}/{database}'
|
||||
if database != 'postgres':
|
||||
setup = {**env, 'DATABASE_URL': url.rsplit('/', 1)[0] + '/postgres'}
|
||||
run(['node', '-e', 'const {PrismaClient}=require("@prisma/client"); const p=new PrismaClient(); '
|
||||
f'p.$executeRawUnsafe(\'CREATE DATABASE "{database}"\')'
|
||||
'.finally(()=>p.$disconnect()).catch(e=>{console.error(e);process.exitCode=1})'], setup)
|
||||
run([BACKEND / 'node_modules/.bin/prisma', 'db', 'push', '--skip-generate'], {**env, 'DATABASE_URL': url})
|
||||
env[key] = url
|
||||
print('Disposable PostgreSQL ready: SEO, publication and corporate integration enabled; '
|
||||
'Stage-principal Redis+/app suites remain explicitly out of scope.', flush=True)
|
||||
run([BACKEND / 'node_modules/.bin/jest', '--runInBand', *sys.argv[1:]], env)
|
||||
finally:
|
||||
failures = []
|
||||
for data in reversed(started):
|
||||
result = subprocess.run([pg_ctl, '-D', str(data), '-m', 'immediate', '-w', '-t', '30', 'stop'], cwd=BACKEND)
|
||||
if result.returncode and (data / 'postmaster.pid').exists():
|
||||
failures.append(str(data))
|
||||
if failures:
|
||||
raise RuntimeError(f'Failed to stop disposable clusters: {failures}')
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
try:
|
||||
main()
|
||||
except (RuntimeError, OSError, subprocess.CalledProcessError) as error:
|
||||
print(f'Backend PostgreSQL test gate failed: {error}', file=sys.stderr)
|
||||
sys.exit(1)
|
||||
@@ -59,16 +59,58 @@ describe("WikiService", () => {
|
||||
where: {
|
||||
OR: [
|
||||
{ term: { contains: "مفصل", mode: "insensitive" } },
|
||||
{ key: { contains: "مفصل", mode: "insensitive" } },
|
||||
{ definition: { contains: "مفصل", mode: "insensitive" } },
|
||||
{ term: { contains: "مفصل", mode: "insensitive" } },
|
||||
{ key: { contains: "مفصل", mode: "insensitive" } },
|
||||
],
|
||||
},
|
||||
skip: 0,
|
||||
take: 10,
|
||||
// Search retrieves bounded candidates, then ranks and slices in memory.
|
||||
skip: undefined,
|
||||
take: 100,
|
||||
orderBy: { term: "desc" },
|
||||
});
|
||||
expect(result.data).toEqual(mockTerms);
|
||||
expect(result.meta.total).toBe(1);
|
||||
expect(result.meta.lastPage).toBe(1);
|
||||
expect(mockPrisma.scientificTerm.count).toHaveBeenCalledWith({
|
||||
where: mockPrisma.scientificTerm.findMany.mock.calls[0][0].where,
|
||||
});
|
||||
});
|
||||
|
||||
it("ranks search candidates before slicing page two and retains filtered total", async () => {
|
||||
const exact = { key: "joint", term: "مفصل", definition: "" };
|
||||
const partial = { key: "joint-care", term: "مفصل سالم", definition: "" };
|
||||
const description = { key: "care", term: "مراقبت", definition: "مفصل" };
|
||||
mockPrisma.scientificTerm.findMany.mockResolvedValue([description, exact, partial]);
|
||||
mockPrisma.scientificTerm.count.mockResolvedValue(3);
|
||||
|
||||
const result = await service.findAll({ search: "مفصل", page: 2, limit: 1 });
|
||||
|
||||
expect(result.data).toEqual([partial]);
|
||||
expect(result.meta).toEqual({
|
||||
total: 3, page: 2, limit: 1, totalPages: 3, lastPage: 3,
|
||||
hasNextPage: true, hasPrevPage: true,
|
||||
});
|
||||
expect(mockPrisma.scientificTerm.findMany).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ skip: undefined, take: 100 }),
|
||||
);
|
||||
});
|
||||
|
||||
it("uses database pagination without search", async () => {
|
||||
mockPrisma.scientificTerm.findMany.mockResolvedValue([]);
|
||||
mockPrisma.scientificTerm.count.mockResolvedValue(12);
|
||||
|
||||
const result = await service.findAll({ page: 2, limit: 10 });
|
||||
|
||||
expect(mockPrisma.scientificTerm.findMany).toHaveBeenCalledWith({
|
||||
where: {}, skip: 10, take: 10, orderBy: { term: "asc" },
|
||||
});
|
||||
expect(mockPrisma.scientificTerm.count).toHaveBeenCalledWith({ where: {} });
|
||||
expect(result.meta).toEqual({
|
||||
total: 12, page: 2, limit: 10, totalPages: 2, lastPage: 2,
|
||||
hasNextPage: false, hasPrevPage: true,
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
@@ -0,0 +1,58 @@
|
||||
import type { CorporateTaskItem } from '../services/hermesApi';
|
||||
|
||||
const value = (n?: number | null) => typeof n === 'number' && Number.isFinite(n) ? n.toLocaleString('fa-IR') : 'ناموجود';
|
||||
const codeClass = 'whitespace-pre-wrap [overflow-wrap:anywhere] text-xs bg-slate-50 p-3 rounded-xl border border-slate-200';
|
||||
|
||||
/** Read-only server record projection; no inference of successful execution or QA. */
|
||||
export default function TaskExecutionDossier({ task }: { task: CorporateTaskItem }) {
|
||||
const evidence = Array.isArray(task.evidence) ? task.evidence : [];
|
||||
const reviews = Array.isArray(task.reviews) ? task.reviews : [];
|
||||
const effects = Array.isArray(task.effects) ? task.effects : [];
|
||||
const truncated = Object.entries(task.relationsMeta ?? {}).filter(([, meta]) => meta?.truncated);
|
||||
return <section aria-label="پرونده اجرای ثبتشده" className="space-y-5 min-w-0 [overflow-wrap:anywhere]">
|
||||
<h3 className="font-bold">پرونده اجرای ثبتشده</h3>
|
||||
<dl className="text-sm space-y-1">
|
||||
<div><dt className="inline font-bold">نوع اقدام: </dt><dd className="inline">{task.actionType}</dd></div>
|
||||
<div><dt className="inline font-bold">مجری تخصیصیافته: </dt><dd className="inline">{task.assignedAgent || 'هنوز تخصیص نیافته'}</dd></div>
|
||||
<div><dt className="inline font-bold">وضعیت ثبتشده: </dt><dd className="inline">{task.status}</dd></div>
|
||||
</dl>
|
||||
{truncated.length > 0 && <p role="status" className="text-amber-800 text-sm">نمایش محدود تاریخچه؛ همه رکوردها دریافت نشدهاند: {truncated.map(([name, meta]) => `${name}: ${meta.returned}/${meta.total}`).join('، ')}</p>}
|
||||
<section aria-label="شواهد اجرایی" className="space-y-3">
|
||||
<h4 className="font-bold text-sm">شواهد اجرایی و نتیجه ابزار</h4>
|
||||
{evidence.length === 0 && <p className="text-sm text-slate-500">هنوز شاهد اجرایی ثبت نشده است.</p>}
|
||||
{evidence.map(item => <article key={item.id} className="space-y-2 border border-slate-200 p-3 rounded-xl min-w-0">
|
||||
<p className="text-sm">{item.summary}</p>
|
||||
<dl className="text-xs space-y-1">
|
||||
<div><dt className="inline font-bold">شناسه شاهد: </dt><dd className="inline">{item.id}</dd></div>
|
||||
<div><dt className="inline font-bold">مجری: </dt><dd className="inline">{item.executor}</dd></div>
|
||||
<div><dt className="inline font-bold">ابزار: </dt><dd className="inline">{item.tool}</dd></div>
|
||||
<div><dt className="inline font-bold">Artifact URI: </dt><dd className="inline" dir="ltr">{item.artifactUri}</dd></div>
|
||||
<div><dt className="inline font-bold">SHA256: </dt><dd className="inline" dir="ltr">{item.sha256}</dd></div>
|
||||
</dl>
|
||||
<pre dir="auto" className={codeClass}>{item.result}</pre>
|
||||
</article>)}
|
||||
</section>
|
||||
<section aria-label="بررسی مستقل کیفیت" className="space-y-3">
|
||||
<h4 className="font-bold text-sm">بررسی مستقل کیفیت</h4>
|
||||
{reviews.length === 0 && <p className="text-sm text-slate-500">هنوز بررسی کیفیت ثبت نشده است.</p>}
|
||||
{reviews.map(item => <article key={item.id} className="space-y-2 border border-slate-200 p-3 rounded-xl min-w-0 text-xs">
|
||||
<p>{item.passed ? 'پذیرفتهشده در رکورد QA' : 'ردشده در رکورد QA'} — {item.reviewer}</p>
|
||||
<p>شناسه شاهد بررسیشده: {item.evidenceId}</p>
|
||||
<p>{item.findings}</p>
|
||||
<p dir="auto">{item.verification?.artifactUri}</p>
|
||||
<p dir="auto">{item.verification?.sha256}</p>
|
||||
<p>{item.verification?.method}</p>
|
||||
<pre dir="auto" className={codeClass}>{item.verification?.result}</pre>
|
||||
</article>)}
|
||||
</section>
|
||||
<section aria-label="اثر و دسترسپذیری آمار" className="space-y-3">
|
||||
<h4 className="font-bold text-sm">اثر و دسترسپذیری آمار</h4>
|
||||
{effects.length === 0 && <p className="text-sm text-slate-500">هنوز اثر اندازهگیریشده یا وضعیت دسترسپذیری ثبت نشده است.</p>}
|
||||
{effects.map(item => <article key={item.id} className="space-y-1 border border-slate-200 p-3 rounded-xl text-xs">
|
||||
<p>{item.metric}</p><p>{item.availability}</p>
|
||||
<p>مبنا: {item.availability === 'MEASURED' ? value(item.baseline) : 'ناموجود'} — مشاهده: {item.availability === 'MEASURED' ? value(item.observed) : 'ناموجود'}</p>
|
||||
<p>{item.source}</p><p>{item.observedAt}</p>
|
||||
</article>)}
|
||||
</section>
|
||||
</section>;
|
||||
}
|
||||
@@ -61,6 +61,38 @@ describe('CorporateTasksPage', () => {
|
||||
await waitFor(() => expect(hermesApi.getTaskById).toHaveBeenCalledWith('t-1', expect.any(AbortSignal)));
|
||||
});
|
||||
|
||||
it('shows persisted tool receipts, exact artifact QA and unavailable effects in a labelled dialog', async () => {
|
||||
vi.mocked(hermesApi.getTaskById).mockResolvedValue({
|
||||
...mockTaskResponse.data[0], status: 'TEST', assignedAgent: 'executor-subject',
|
||||
evidence: [{ id: 'e', artifactUri: 'urn:sha256:' + 'a'.repeat(64), sha256: 'a'.repeat(64),
|
||||
executor: 'executor-subject', tool: 'python:department_audit_v1', summary: 'Observed structural audit', result: 'actual tool receipt', createdAt: '2026-10-28T01:00:00Z' }],
|
||||
reviews: [{ id: 'r', evidenceId: 'e', reviewer: 'reviewer-subject', passed: false, findings: 'Reopen source bytes',
|
||||
verification: { artifactUri: 'urn:sha256:' + 'a'.repeat(64), sha256: 'a'.repeat(64), method: 'exact-byte reopen', result: 'hash verified' } }],
|
||||
effects: [{ id: 'm', metric: 'organic_engagement', availability: 'UNINSTRUMENTED', observed: null, baseline: null, source: 'No instrumentation' }],
|
||||
relationsMeta: { evidence: { total: 101, returned: 100, limit: 100, truncated: true } },
|
||||
});
|
||||
render(<CorporateTasksPage />);
|
||||
expect(screen.getByRole('option', { name: 'در انتظار بررسی کیفیت' })).toHaveValue('TEST');
|
||||
fireEvent.click(await screen.findByRole('button', { name: /جزئیات و مکالمات/ }));
|
||||
expect(await screen.findByRole('dialog', { name: /انتشار مقاله بالینی/ })).toBeDefined();
|
||||
expect(screen.getByText('python:department_audit_v1')).toBeDefined();
|
||||
expect(screen.getByText('actual tool receipt')).toBeDefined();
|
||||
expect(screen.getByText('exact-byte reopen')).toBeDefined();
|
||||
expect(screen.getByText('hash verified')).toBeDefined();
|
||||
expect(screen.getByText('UNINSTRUMENTED')).toBeDefined();
|
||||
expect(screen.getByText('No instrumentation')).toBeDefined();
|
||||
expect(screen.getByText(/نمایش محدود تاریخچه/)).toBeDefined();
|
||||
expect(screen.getByRole('button', { name: 'بستن جزئیات' })).toBeDefined();
|
||||
});
|
||||
|
||||
it('distinguishes absent execution evidence from completion', async () => {
|
||||
render(<CorporateTasksPage />);
|
||||
fireEvent.click(await screen.findByRole('button', { name: /جزئیات و مکالمات/ }));
|
||||
expect(await screen.findByText('هنوز شاهد اجرایی ثبت نشده است.')).toBeDefined();
|
||||
expect(screen.getByText('هنوز بررسی کیفیت ثبت نشده است.')).toBeDefined();
|
||||
expect(screen.getByText('هنوز اثر اندازهگیریشده یا وضعیت دسترسپذیری ثبت نشده است.')).toBeDefined();
|
||||
});
|
||||
|
||||
it('shows creation failure and retains entered directive', async () => {
|
||||
vi.mocked(hermesApi.createCeoTask).mockRejectedValue(new Error('not saved'));
|
||||
render(<CorporateTasksPage />);
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { useEffect, useRef, useState } from 'react';
|
||||
import { createPortal } from 'react-dom';
|
||||
import TaskExecutionDossier from '../components/TaskExecutionDossier';
|
||||
import { safeHttpUrl } from '../components/HermesSource';
|
||||
import {
|
||||
ListOrdered,
|
||||
@@ -35,6 +36,7 @@ const deptConfig: Record<TaskDepartment, { label: string; bg: string; text: stri
|
||||
const statusConfig: Record<TaskStatus, { label: string; bg: string; text: string; border: string }> = {
|
||||
TODO: { label: 'در صف نوبت', bg: 'bg-slate-100', text: 'text-slate-600', border: 'border-slate-200' },
|
||||
IN_PROGRESS: { label: 'در حال انجام', bg: 'bg-sky-50', text: 'text-sky-700', border: 'border-sky-200' },
|
||||
TEST: { label: 'در انتظار بررسی کیفیت', bg: 'bg-violet-50', text: 'text-violet-700', border: 'border-violet-200' },
|
||||
DONE: { label: 'انجامشده', bg: 'bg-emerald-50', text: 'text-emerald-700', border: 'border-emerald-200' },
|
||||
BLOCKED: { label: 'مسدود', bg: 'bg-rose-50', text: 'text-rose-700', border: 'border-rose-200' },
|
||||
CANCELLED: { label: 'لغوشده', bg: 'bg-gray-100', text: 'text-gray-500', border: 'border-gray-200' },
|
||||
@@ -481,7 +483,7 @@ export default function CorporateTasksPage() {
|
||||
{selectedTask &&
|
||||
createPortal(
|
||||
<div className="fixed inset-0 z-50 bg-slate-900/60 backdrop-blur-xs flex items-center justify-center p-3 sm:p-6" dir="rtl">
|
||||
<div className="bg-white rounded-3xl shadow-2xl w-full max-w-4xl max-h-[92vh] flex flex-col overflow-hidden border border-slate-200">
|
||||
<div role="dialog" aria-modal="true" aria-labelledby="corporate-task-title" className="bg-white rounded-3xl shadow-2xl w-full max-w-4xl max-h-[92vh] flex flex-col overflow-hidden border border-slate-200">
|
||||
{/* هدر مودال */}
|
||||
<div className="flex items-center justify-between gap-4 px-6 py-4 border-b border-slate-200 bg-slate-50/70">
|
||||
<div className="flex items-center gap-3">
|
||||
@@ -493,7 +495,7 @@ export default function CorporateTasksPage() {
|
||||
<span className="font-mono text-xs font-bold text-slate-500 bg-slate-200 px-2 py-0.5 rounded">
|
||||
{selectedTask.taskCode}
|
||||
</span>
|
||||
<h2 className="font-black text-base sm:text-lg text-slate-900 leading-snug">
|
||||
<h2 id="corporate-task-title" className="font-black text-base sm:text-lg text-slate-900 leading-snug">
|
||||
{selectedTask.title}
|
||||
</h2>
|
||||
</div>
|
||||
@@ -504,6 +506,7 @@ export default function CorporateTasksPage() {
|
||||
</div>
|
||||
<button
|
||||
className="p-2 rounded-xl text-slate-500 hover:text-slate-800 hover:bg-slate-200/80 transition-colors cursor-pointer"
|
||||
aria-label="بستن جزئیات"
|
||||
onClick={() => { setSelectedTask(null); setDetailId(null); }}
|
||||
>
|
||||
<X className="w-5 h-5" />
|
||||
@@ -532,6 +535,8 @@ export default function CorporateTasksPage() {
|
||||
)}
|
||||
</div>
|
||||
|
||||
<TaskExecutionDossier task={selectedTask} />
|
||||
|
||||
{/* تایملاین ریز مکالمات و لاگ اقدام ایجنتها */}
|
||||
<div className="space-y-4">
|
||||
<div className="flex items-center gap-2 pb-2 border-b border-slate-100">
|
||||
|
||||
@@ -9,7 +9,21 @@ export type TaskDepartment =
|
||||
|
||||
export type TaskPriority = 'CEO_EXPEDITE' | 'CRITICAL' | 'HIGH' | 'MEDIUM' | 'LOW';
|
||||
|
||||
export type TaskStatus = 'TODO' | 'IN_PROGRESS' | 'DONE' | 'BLOCKED' | 'CANCELLED';
|
||||
export type TaskStatus = 'TODO' | 'IN_PROGRESS' | 'TEST' | 'DONE' | 'BLOCKED' | 'CANCELLED';
|
||||
|
||||
export interface TaskEvidence {
|
||||
id: string; artifactUri: string; sha256: string; executor: string;
|
||||
tool: string; summary: string; result: string; createdAt?: string;
|
||||
}
|
||||
export interface TaskReview {
|
||||
id: string; evidenceId: string; reviewer: string; passed: boolean; findings: string;
|
||||
verification: { artifactUri?: string; sha256?: string; method?: string; result?: string };
|
||||
}
|
||||
export interface TaskEffect {
|
||||
id: string; metric: string; availability: string; baseline?: number | null;
|
||||
observed?: number | null; source: string; observedAt?: string;
|
||||
}
|
||||
export interface RelationMeta { total: number; returned: number; limit: number; truncated: boolean }
|
||||
|
||||
export interface TaskLogItem {
|
||||
id: string;
|
||||
@@ -39,6 +53,10 @@ export interface CorporateTaskItem {
|
||||
createdAt: string;
|
||||
updatedAt: string;
|
||||
logs?: TaskLogItem[];
|
||||
evidence?: TaskEvidence[];
|
||||
reviews?: TaskReview[];
|
||||
effects?: TaskEffect[];
|
||||
relationsMeta?: Record<string, RelationMeta>;
|
||||
}
|
||||
|
||||
export interface TaskFilterParams {
|
||||
|
||||
@@ -0,0 +1,7 @@
|
||||
# Plan
|
||||
|
||||
Ownership: backend/src/wiki/wiki.service.spec.ts; backend/scripts/test-postgres.py; backend/package.json test scripts; this spec directory only. No corporate service/runtime or UI files.
|
||||
|
||||
Graphify: queried scratch copy at /opt/data/cache/scratch/backend-acceptance-graph (4304 nodes). Original SHA256 6a73473cee9e207543fdeeb668bea544f766200a1b16b8a3a9ce18d4e42e51af; provenance not SHA-bound, navigation only. Direct source confirms WikiService reads relevance candidates (take 100), ranks then slices; shared metadata helper uses totalPages and compatibility lastPage. Existing publication URL guard mandates port 55447; SEO mandates port 55439; corporate mandates loopback corporate_test. Tests destructively clean fixtures, so only newly initialized clusters are eligible.
|
||||
|
||||
Runner uses existing PostgreSQL binaries via PG_BIN or PATH, mkdtemp under TMPDIR, explicit loopback ports/private sockets, Prisma db push into newly created databases, child-only test URLs and guaranteed pg_ctl stop in finally. No daemon reuse. Default test runs serially to avoid shared fixture collisions. Direct Jest remains available for explicit targeted unit tests; the default npm test gate never silently skips missing PostgreSQL URLs.
|
||||
@@ -0,0 +1,11 @@
|
||||
# Backend acceptance test gates
|
||||
|
||||
Scope: wiki unit-test expectations and isolated PostgreSQL full-suite setup only. No service/runtime/UI edits, deployment, cron, production configuration or business-data writes.
|
||||
|
||||
Acceptance:
|
||||
- Wiki tests distinguish bounded relevance candidate retrieval from final page slicing and verify filtered count metadata; non-search pagination remains database-driven.
|
||||
- Default backend test command provisions disposable loopback PostgreSQL and executes publication, SEO and corporate database integration suites instead of silently skipping missing URLs.
|
||||
- Missing PostgreSQL binaries or occupied dedicated ports fail explicitly. Existing runtime DATABASE_URL is never used for schema setup.
|
||||
- Preserve existing dirty/untracked work. Stage-principal tests are separate opt-in tests requiring Redis and /app artifacts; report their skips explicitly.
|
||||
|
||||
Baseline: develop 69dd6922f6ce25e5b98471b14282b7834537431a. Initial dirty state: graphify-out/cache/last_query_stamp; untracked .specify/ and evidence/. RED full suite: 2 failed, 99 passed, 6 skipped; 1 failed/905 passed/25 skipped tests.
|
||||
@@ -0,0 +1,20 @@
|
||||
# Tasks
|
||||
|
||||
- [x] Inspect source, graph provenance, branch, dirty state and existing tests.
|
||||
- [x] Run baseline full suite RED and retain /opt/data/cache/scratch/backend-suite-red.log.
|
||||
- [x] Correct wiki expectations; add ranking/page-2 and non-search pagination checks.
|
||||
- [x] Implement disposable PostgreSQL runner and default test command; fail closed on setup failure.
|
||||
- [x] Run full backend GREEN, record commands/counts and explicit remaining skips; verify owned diff only.
|
||||
|
||||
## Execution evidence
|
||||
|
||||
Working directory for commands: `/opt/data/content-maintenance/engine/worktree-concurrency-tdd/backend`.
|
||||
- RED before edits: `npm test -- --runInBand` (then direct Jest script): 2 failed, 99 passed, 6 skipped suites; 1 failed, 905 passed, 25 skipped tests. `/opt/data/cache/scratch/backend-suite-red.log`.
|
||||
- GREEN: `PG_BIN=/opt/data/cache/scratch/seo-pg-bin/bin npm test`: exit 0, 105 passed and 2 skipped suites; 934 passed and 3 skipped tests, 62.56s. `/opt/data/cache/scratch/backend-suite-green.log`. All SEO, publication, corporate and API-key PostgreSQL suites executed. Remaining skips are two Stage-principal lifecycle suites (Redis and `/app` prerequisites), not missing database URLs.
|
||||
- `PG_BIN=/does-not-exist npm test`: expected exit 1, explicit missing-initdb failure. `/opt/data/cache/scratch/backend-pg-missing-bin.log`.
|
||||
- Bind 127.0.0.1:55439 in a Python socket then invoke runner: expected exit 1, address in use. No existing server reused or stopped.
|
||||
- `npm run build`: exit 0 (`tsc -b`). `git diff --check`: exit 0.
|
||||
- All three fresh PostgreSQL 16.2 clusters stopped after full suite and temporary cluster directory removed. No production connection or configuration accessed. Existing dirty graph stamp and untracked .specify/evidence preserved.
|
||||
|
||||
Setup detail: publication's existing source URL allowlist contains a dedicated test-only credential. Runner reads and validates its literal loopback prefix to avoid duplicating it; first execution exposed that redacted tool display must not be treated as the credential itself. No change to publication or corporate test/service files was necessary. Docker unavailable; reused already-installed local PostgreSQL binaries, with no package installation.
|
||||
|
||||
@@ -0,0 +1,31 @@
|
||||
# Bounded acceptance-gap audit
|
||||
|
||||
Baseline: develop 69dd6922f6ce25e5b98471b14282b7834537431a, official Stage run1352. Audit is bounded to existing specs, runtime scripts, corporate service/controller, UI/services and focused/full-suite evidence; not a claim of enterprise acceptance.
|
||||
|
||||
| Criterion | Code/tests | Deployment/behavior | Verdict / next dependency |
|
||||
|---|---|---|---|
|
||||
| Real persisted source provenance | corporate research/source tables, validated HTTPS metadata, manual ingest stores fetched bytes and SHA256 | Baseline both Stage images independently read as 69dd6922, restart0; source inventory pilot exists, not autonomous business research | partial: discovery/synthesis and provider-backed intelligence missing |
|
||||
| Monthly research -> persisted roadmap/goals | service roadmap requires persisted research with sources; manual CLI manifest | Existing integration tests; no demonstrated automatic strategy synthesis | partial |
|
||||
| Daily NEW article plan separate from refresh | UI promises daily new; roadmap counts only; fanout creates source inventories | No dated article planning or article executor | missing |
|
||||
| Needs-based refresh/catalog/wiki/engineering/devops | dormant deterministic structural department audits and GET-only plan_day | Not clinical enrichment, code execution, or publication; plan is not persisted task fanout | partial |
|
||||
| Atomic claim/execution/evidence/independent QA | service lease fencing, idempotency, TEST, distinct review identity, exact hash verification | Existing real disposable DB tests and source-inventory pilot | partial: only manual bounded inventory/audits, no business action adapters |
|
||||
| Visible instruction/action/result/evidence/QA | Task detail shows description and event summaries only; evidence/reviews/effects omitted; TEST absent in frontend status type/filter | API detail includes these relations; UI cannot inspect exact receipts | **missing next slice**: read-only persisted execution dossier + TEST status |
|
||||
| PMO outcomes/report | persisted backend report snapshots, explicit truncation; manual GET-only plan | No integrated daily plan/report consumer or report UI | partial |
|
||||
| Market pagination/filter/search | pagination/category UI + backend; no search | Not authenticated/mobile accepted in this audit yet | partial |
|
||||
| Roadmap pagination/filter/search | pagination UI, month backend only; no search | Not authenticated/mobile accepted yet | partial |
|
||||
| Tasks pagination/filter/search | server pagination, normalized title/code, dept/status/priority | Missing TEST option; execution dossier absent | partial |
|
||||
| SEO under Hermes/mobile | existing tracking page and API, independent telemetry limits | Requires distinct authenticated mobile review, not proven by compile | partial |
|
||||
| No fake fallback | APIs reject unavailable collections; UI explicit errors; metrics unavailable != zero | Preserve; no demo business data added | code present, scoped verification required |
|
||||
| Test gates | baseline full Jest: 2 failures incl wiki expectation and absent isolated DB URLs | Repair full gate with fresh private PostgreSQL harness, no live DB reuse | partial until repaired run |
|
||||
| Public author attribution | credentialless genuine authors restored; marker denied all auth paths | Baseline API repair confirmed by parent; public attribution UI still unresolved | partial; inspect real byline/metadata, never invent credentials/clinical expertise |
|
||||
| Autonomous operation | runtime explicitly MANUAL_DORMANT, schedules false | Must remain cron-disconnected until whole acceptance | deliberately not enabled |
|
||||
|
||||
## Slice selection
|
||||
First unblock truthful inspection of persisted execution: without exact tool/result/hash and independent QA visible, a higher-level planner would create more uninspectable tasks. Implement read-only dossier, real TEST status/filter, empty and bounded-history disclosures. No schema/business writes, new scheduler, approval modules, Hermes config/restarts, Production or main changes.
|
||||
|
||||
## Remaining sequence
|
||||
1. Accept this dossier and corrected isolated DB gate on exact-SHA Stage.
|
||||
2. Research-backed dated daily-new article planning, separate needs-based refresh/catalog/wiki/engineering task lineage, API idempotent persistence (review schema separately if needed).
|
||||
3. Implement narrowly allowed action adapters with immutable instruction/action/result/evidence and independent QA; no model-output-is-DONE shortcuts.
|
||||
4. Persist PMO outcomes and downstream daily plan; add market/roadmap search/filter/report UI, finish authenticated mobile acceptance and real public author checks.
|
||||
5. Only after complete independent acceptance consider explicit activation of the currently dormant/manual runtime; no cron changes in this program slice.
|
||||
@@ -0,0 +1,11 @@
|
||||
{
|
||||
"baseSha": "69dd6922f6ce25e5b98471b14282b7834537431a",
|
||||
"graphSha256": "6a73473cee9e207543fdeeb668bea544f766200a1b16b8a3a9ce18d4e42e51af",
|
||||
"graphSourceBinding": "unknown; stale navigation only, verified direct source",
|
||||
"queryCopy": "/opt/data/cache/scratch/corporate-gap-graph/graph.json",
|
||||
"dirtyBefore": [
|
||||
"graphify-out/cache/last_query_stamp",
|
||||
".specify/",
|
||||
"evidence/"
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
# Plan
|
||||
|
||||
Baseline 69dd6922. Existing graph SHA binding unknown: SHA256 recorded in graph-provenance.json, query scratch copy finds stale unrelated Evidence/review nodes, used only navigation; direct corporate service/controller and UI sources verified. API already returns evidence/reviews/effects/relationsMeta. Add typed optional relation DTOs plus read-only TaskExecutionDossier component rendered inside existing fetched detail. Include TEST type/config. Own UI/API types/tests; backend test gate child owns disjoint paths. Use existing release workflow and gitea remote, never local bundle origin for push.
|
||||
@@ -0,0 +1,3 @@
|
||||
# Persisted execution dossier
|
||||
|
||||
Show existing authenticated task detail instruction, action type, assigned executor, exact evidence tool/result/URI/hash, independent QA verification and observed effects. TEST is a real selectable status. Read-only: no action buttons, claims or synthetic fallback. Empty evidence and missing metrics must not imply success. Expose relation truncation. Wrap long hashes/results on 390px; semantic labelled dialog with close button. Unit regression RED before UI edit; full admin tests/typecheck/build, backend full fresh PostgreSQL suite, storefront suite/build then exact-SHA Stage authenticated mobile acceptance. No schema, prod/main, cron/Hermes config or business-data SQL writes.
|
||||
@@ -0,0 +1,8 @@
|
||||
# Tasks
|
||||
|
||||
- [x] Bounded acceptance audit, source/API boundary review, preserve baseline untracked artifacts.
|
||||
- [ ] Dossier and TEST regression RED.
|
||||
- [ ] Minimal typed read-only dossier GREEN; full suites/build.
|
||||
- [ ] Integrated source review, sole-owner develop push.
|
||||
- [ ] Exact CI terminal logs, both images/restarts, authenticated Stage/mobile dossier + public real author UI evidence.
|
||||
- [ ] Record remaining acceptance gaps without whole-program readiness claim.
|
||||
Reference in new issue
Block a user